iOS-圆环统计图(CircleChart)

前言:圆环统计图在我们工程中比较常用,正好我们公司项目中要用到,所以自己封装了一下,以方便以后复用。


首先,我们看一下效果图:

圆环效果图.png

其次,实现原理也是比较简单的,底部是一个圆,上面同样位置现叠加一个有会值的圆,中间的文字引用第三方框架***UICountingLabel ***

使用起来也非常简单

    GBCircleChart *circleChart = [[GBCircleChart alloc] initWithFrame:CGRectMake(0, 100, CGRectGetWidth(self.view.frame), 200) total:@100 current:@30 clockwise:YES shadow:YES shadowColor:[[UIColor grayColor] colorWithAlphaComponent:0.4] displayCountingLabel:YES overrideLineWidth:@4];
    [self.view addSubview:circleChart];
    circleChart.strokeColorGradientStart = [UIColor blueColor];
    circleChart.strokeColor = [UIColor redColor];
//    circleChart.shadowColor = [UIColor blueColor];
    circleChart.countingLabel.formatBlock = ^NSString *(CGFloat value) {
      
        return [NSString stringWithFormat:@"%0.0f分\n我的成绩单", value];
    };
    [circleChart strokeChart];
    _circleChart = circleChart;

我们来看一下.h文件中包含哪些方法和属性:

#import <UIKit/UIKit.h>
#import "UICountingLabel.h"

@interface GBCircleChart : UIView
#pragma mark - 属性
/** 计数Label */
@property (strong, nonatomic) UICountingLabel *countingLabel;
/** 圆环颜色 */
@property (nonatomic) UIColor *strokeColor;
/** 开始渐变颜色 */
@property (nonatomic) UIColor *strokeColorGradientStart;
/** 圆环的阴影颜色,默认为nil */
@property (nonatomic) UIColor *shadowColor;
/** 最大的值 */
@property (nonatomic) NSNumber *total;
/** 当前的值 */
@property (nonatomic) NSNumber *current;
/** 线宽 */
@property (nonatomic) NSNumber *lineWidth;
/** 动画持续时长 */
@property (nonatomic) NSTimeInterval duration;
/** 是否显示文字 */
@property (nonatomic) BOOL displayCountingLabel;
/** 是否动画,默认yes */
@property (nonatomic) BOOL displayAnimated;

#pragma mark - 初始化方法
- (id)initWithFrame:(CGRect)frame
              total:(NSNumber *)total
            current:(NSNumber *)current
          clockwise:(BOOL)clockwise;

- (id)initWithFrame:(CGRect)frame
              total:(NSNumber *)total
            current:(NSNumber *)current
          clockwise:(BOOL)clockwise
             shadow:(BOOL)hasBackgroundShadow
        shadowColor:(UIColor *)backgroundShadowColor;

- (id)initWithFrame:(CGRect)frame
              total:(NSNumber *)total
            current:(NSNumber *)current
          clockwise:(BOOL)clockwise
             shadow:(BOOL)hasBackgroundShadow
        shadowColor:(UIColor *)backgroundShadowColor
displayCountingLabel:(BOOL)displayCountingLabel;

-  (id)initWithFrame:(CGRect)frame
               total:(NSNumber *)total
             current:(NSNumber *)current
           clockwise:(BOOL)clockwise
              shadow:(BOOL)hasBackgroundShadow
         shadowColor:(UIColor *)backgroundShadowColor
displayCountingLabel:(BOOL)displayCountingLabel
   overrideLineWidth:(NSNumber *)overrideLineWidth;

#pragma mark - 绘制或更新图表
- (void)strokeChart;
- (void)growChartByAmount:(NSNumber *)growAmount;
- (void)updateChartByCurrent:(NSNumber *)current;
- (void)updateChartByCurrent:(NSNumber *)current byTotal:(NSNumber *)total;
@end

然后,我们再看一下.m中的实现

#import "GBCircleChart.h"

@interface GBCircleChart ()

@property (nonatomic) CAShapeLayer *circle;
@property (nonatomic) CAShapeLayer *gradientMask;
@property (nonatomic) CAShapeLayer *circleBackground;

@end

@implementation GBCircleChart

- (id)initWithFrame:(CGRect)frame total:(NSNumber *)total current:(NSNumber *)current clockwise:(BOOL)clockwise {

    return [self initWithFrame:frame total:total current:current clockwise:clockwise shadow:NO shadowColor:[UIColor clearColor]];
}

- (id)initWithFrame:(CGRect)frame total:(NSNumber *)total current:(NSNumber *)current clockwise:(BOOL)clockwise shadow:(BOOL)hasBackgroundShadow shadowColor:(UIColor *)backgroundShadowColor {
    
    return [self initWithFrame:frame total:total current:current clockwise:clockwise shadow:hasBackgroundShadow shadowColor:backgroundShadowColor displayCountingLabel:YES];
}

- (id)initWithFrame:(CGRect)frame total:(NSNumber *)total current:(NSNumber *)current clockwise:(BOOL)clockwise shadow:(BOOL)hasBackgroundShadow shadowColor:(UIColor *)backgroundShadowColor displayCountingLabel:(BOOL)displayCountingLabel {
    
    return [self initWithFrame:frame total:total current:current clockwise:clockwise shadow:hasBackgroundShadow shadowColor:backgroundShadowColor displayCountingLabel:displayCountingLabel overrideLineWidth:@8];
}

- (id)initWithFrame:(CGRect)frame total:(NSNumber *)total current:(NSNumber *)current clockwise:(BOOL)clockwise shadow:(BOOL)hasBackgroundShadow shadowColor:(UIColor *)backgroundShadowColor displayCountingLabel:(BOOL)displayCountingLabel overrideLineWidth:(NSNumber *)overrideLineWidth {
    
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor whiteColor];
        _total = total;
        _current = current;
        _strokeColor = [UIColor blueColor];
        _lineWidth = overrideLineWidth;
        _duration = 1.0;
        _displayAnimated = YES;
        _displayCountingLabel = displayCountingLabel;
        
        CGPoint center = CGPointMake(frame.size.width/2, frame.size.height/2);
        CGFloat r = MIN(CGRectGetWidth(frame), CGRectGetHeight(frame))/2 - _lineWidth.floatValue/2;
        UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:r startAngle:-M_PI_2 endAngle:-M_PI_2+2*M_PI clockwise:clockwise];
        
        _circle = [CAShapeLayer layer];
        _circle.lineWidth = _lineWidth.floatValue;
        _circle.lineCap = kCALineCapRound;
        _circle.strokeColor = _strokeColor.CGColor;
        _circle.fillColor = [UIColor clearColor].CGColor;
        _circle.path = path.CGPath;
        [self.layer addSublayer:_circle];
        
        if (hasBackgroundShadow) {
            _circleBackground = [CAShapeLayer layer];
            _circleBackground.lineWidth = _lineWidth.floatValue;
            _circleBackground.lineCap = kCALineCapRound;
            _circleBackground.strokeColor = backgroundShadowColor.CGColor;
            _circleBackground.fillColor = [UIColor clearColor].CGColor;
            _circleBackground.path = path.CGPath;
            [self.layer addSublayer:_circleBackground];
        }
        
        if (_displayCountingLabel) {
            _countingLabel = [[UICountingLabel alloc] initWithFrame:CGRectMake(0, 0, 2*(r - 20), 2*(r - 20))];
            _countingLabel.center = center;
            _countingLabel.textColor = [UIColor darkTextColor];
            _countingLabel.font = [UIFont systemFontOfSize:16];
            _countingLabel.textAlignment = NSTextAlignmentCenter;
            _countingLabel.numberOfLines = 0;
//            _countingLabel.backgroundColor = [UIColor lightGrayColor];
            _countingLabel.method = UILabelCountingMethodEaseInOut;
            _countingLabel.format = @"%.1f%%";
            [self addSubview:_countingLabel];
        }
        
    }
    return self;
}

- (void)strokeChart {
    
    if (_shadowColor) {
        _circle.shadowColor = _shadowColor.CGColor;
        _circle.shadowRadius = 3;
        _circle.shadowOpacity = 0.5;
        _circle.shadowOffset = CGSizeMake(0, 0);
    }
    _circle.strokeColor = _strokeColor.CGColor;

    _circle.strokeEnd = _current.floatValue/_total.floatValue;
    if (_displayCountingLabel) {
        CGFloat totalPercentageValue = [_current floatValue]/([_total floatValue]/100.0);
        [_countingLabel countFromZeroTo:totalPercentageValue withDuration:_duration];
    }
    if (_strokeColorGradientStart) {

        self.gradientMask = [CAShapeLayer layer];
        self.gradientMask.fillColor = [[UIColor clearColor] CGColor];
        self.gradientMask.strokeColor = [[UIColor blackColor] CGColor];
        self.gradientMask.lineWidth = _circle.lineWidth;
        self.gradientMask.lineCap = kCALineCapRound;
        CGRect gradientFrame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
        self.gradientMask.frame = gradientFrame;
        self.gradientMask.path = _circle.path;

        CAGradientLayer *gradientLayer = [CAGradientLayer layer];
        gradientLayer.startPoint = CGPointMake(0.5, 0.0);
        gradientLayer.endPoint = CGPointMake(0.5, 1.0);
        gradientLayer.colors = @[(id)_strokeColorGradientStart.CGColor, (id)_strokeColor.CGColor];
        gradientLayer.frame = gradientFrame;
        gradientLayer.mask = _gradientMask;

        [_circle addSublayer:gradientLayer];

        _gradientMask.strokeEnd = _current.floatValue/_total.floatValue;
    }
    if (_displayAnimated) {
        [self addAnimationIfNeededWithFromValue:@0 toValue:@(_current.floatValue/_total.floatValue)];
    }
}

- (void)updateChartByCurrent:(NSNumber *)current {
    
    [self updateChartByCurrent:current byTotal:_total];
}

- (void)updateChartByCurrent:(NSNumber *)current byTotal:(NSNumber *)total {
    
    _circle.strokeEnd = current.floatValue/total.floatValue;
    
    if (_strokeColorGradientStart && _gradientMask) {
        _gradientMask.strokeEnd = _circle.strokeEnd;
    }
    
    if (_displayCountingLabel) {
        CGFloat totalPercentageValue = [current floatValue]/([total floatValue]/100.0);
        [_countingLabel countFrom:_current.floatValue to:totalPercentageValue withDuration:_duration];
    }
    [self addAnimationIfNeededWithFromValue:@(_current.floatValue/_total.floatValue) toValue:@(current.floatValue/total.floatValue)];

    _current = current;
    _total = total;
}

- (void)growChartByAmount:(NSNumber *)growAmount {
    
    NSNumber *currrentNumber = @(_current.floatValue + growAmount.floatValue);
    [self updateChartByCurrent:currrentNumber byTotal:_total];
}

- (void)addAnimationIfNeededWithFromValue:(NSNumber *)fromValue toValue:(NSNumber *)toValue{
    
    CABasicAnimation *ani = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    ani.fromValue = fromValue;
    ani.toValue = toValue;
    ani.duration = _duration;
    ani.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [_circle addAnimation:ani forKey:nil];
    if (_gradientMask && _strokeColorGradientStart) {
        [_gradientMask addAnimation:ani forKey:nil];
    }
}

大功告成,最后当然是附上demo和源代码了,希望下载与指正哦~~~~
传送门:demo下载

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,290评论 6 491
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,107评论 2 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 156,872评论 0 347
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,415评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,453评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,784评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,927评论 3 406
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,691评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,137评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,472评论 2 326
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,622评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,289评论 4 329
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,887评论 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,741评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,977评论 1 265
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,316评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,490评论 2 348

推荐阅读更多精彩内容