iOS 画个简单的饼图

闲来无事,把之前仿照网友敲的饼图代码传上来,供以后查看,先看看效果图:


pie_pic1.jpg
pie_pic2.jpg
  1. 先创建一个CAShapeLayer子类,这个是饼图的数据元素所用的layer,方便计算角度
#import "YBKCustomPieView.h"

@interface YBKCustomPieLayer : CAShapeLayer
@property (nonatomic, assign) CGFloat startAngle;
@property (nonatomic, assign) CGFloat endAngle;
@property (nonatomic, assign) BOOL isSelected;

@end
@implementation YBKCustomPieLayer
@end
  1. YBKCustomPieView所需属性
#define kWidth_Self         self.bounds.size.width
#define kHeight_Self        self.bounds.size.height
#define kSpace_PointToPie   10
#define kSpace_LineTurning   20 //指示线线转折的距离

@interface YBKCustomPieView ()
{
    CAShapeLayer *bgLayer;        //饼图背景bgLayer
    CAShapeLayer *maskLayer;    //附加的动画效果所用的遮罩maskLayer
}

//数据数组
@property (nonatomic, strong) NSArray *dataArr;
//百分比数组
@property (nonatomic, strong) NSArray *numberArr;
//文字数组
@property (nonatomic, strong) NSArray *titleArr;
//颜色数组
@property (nonatomic, strong) NSArray *colorArr;
//圆半径
@property (nonatomic, assign) CGFloat radius;
//圆环宽度
@property (nonatomic, assign) CGFloat circleWidth;

@end
  1. 下面是@implementation YBKCustomPieView中的代码

初始化

- (instancetype)initWithFrame:(CGRect)frame WithRadius:(CGFloat)radius CircleWidth:(CGFloat)circleWidth DataArr:(NSArray *)dataArr {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.radius = radius;
        self.circleWidth = circleWidth;
        //如果图片路径大于弧度,显示出来的圆弧有交叉;width=radius,显示整好为实心圆;width<radius,显示的是空心圆环
        if (circleWidth > radius) {
            self.circleWidth = radius;
        }
        self.dataArr = dataArr;
    }
    return self;
}

重写dataArr的set方法,在这里计算其他数组的值

-(void)setDataArr:(NSArray *)dataArr { 
    CGFloat sumValue = [[dataArr valueForKeyPath:@"number.@sum.floatValue"] floatValue];
    NSArray *tmpArray = sumValue < 1 ? [dataArr arrayByAddingObject:@{@"number":[NSString stringWithFormat:@"%f", 1 - sumValue], @"city":@"其他"}] : dataArr;
    
    tmpArray = [tmpArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        if ([obj1[@"number"] floatValue] < [obj2[@"number"] floatValue]) {
            return NSOrderedDescending;
        } else {
            return NSOrderedAscending;
        }
    }];
    
    _dataArr = tmpArray;
    
//    对象操作:针对数组的情况
//    @distinctUnionOfObjects:返回指定属性去重后的值的数组
//    @unionOfObjects:返回指定属性的值的数组,不去重
//    属性的值不能为空,否则产生异常。
//
//    数组操作:针对数组的数组情况
//    @distinctUnionOfArrays:返回指定属性去重后的值的数组
//    @unionOfArrays:返回指定属性的值的数组,不去重
//    @distinctUnionOfSets:同上,只是返回值为NSSet

    _numberArr = [tmpArray valueForKeyPath:@"@unionOfObjects.number"];
    _titleArr = [tmpArray valueForKeyPath:@"@unionOfObjects.city"];
    NSMutableArray *colorArr = [NSMutableArray arrayWithCapacity:0];
    
    for (int i = 0; i < _numberArr.count; i++) {
        [colorArr addObject:[UIColor colorWithRed:(arc4random() % 245 + 10) / 255.0 green:(arc4random() % 245 + 10) / 255.0 blue:(arc4random() % 245 + 10) / 255.0 alpha:1.f]];
    }
    _colorArr = colorArr;
}

在- (void)drawRect:(CGRect)rect方法中绘制图形,初始化bgLayer和遮罩maskLayer

- (void)drawRect:(CGRect)rect {
    while (self.layer.sublayers.count > 0) {
        [self.layer.sublayers.firstObject removeFromSuperlayer];
    }
    bgLayer = [CAShapeLayer layer];
    bgLayer.fillColor = [UIColor clearColor].CGColor;
    bgLayer.frame = CGRectMake(CGRectGetMidX(self.bounds) - self.radius, CGRectGetMidY(self.bounds) - self.radius, self.radius * 2, self.radius * 2);
    
    UIBezierPath *bgPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(CGRectGetMidX(bgLayer.bounds), CGRectGetMidY(bgLayer.bounds)) radius:self.radius startAngle:0 endAngle:2 * M_PI clockwise:NO];
    bgLayer.path = bgPath.CGPath;
    [self.layer addSublayer:bgLayer];
    
    [self addData];
    //遮罩
    maskLayer = [CAShapeLayer layer];

    CGFloat maskHeight = self.bounds.size.width > self.bounds.size.height ? self.bounds.size.height : self.bounds.size.width;
    maskLayer.frame = CGRectMake(CGRectGetMidX(self.bounds) - maskHeight / 2, CGRectGetMidY(self.bounds) - maskHeight / 2, maskHeight, maskHeight);
    
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(CGRectGetMidX(maskLayer.bounds), CGRectGetMidY(maskLayer.bounds)) radius:maskHeight / 4 startAngle:0 endAngle:M_PI * 2 clockwise:NO];
    maskLayer.fillColor = [UIColor clearColor].CGColor;
    maskLayer.strokeColor = self.backgroundColor.CGColor;
    maskLayer.lineWidth = maskHeight / 2;
    maskLayer.path = maskPath.CGPath;
    maskLayer.strokeEnd = 0;
    [self.layer addSublayer:maskLayer];
}

开始根据data数据的百分比,来绘制饼图中的元素

- (void)addData {

    CGFloat start = 0;
    CGFloat end = start;
    
    for (int i = 0; i < self.numberArr.count; i++) {
        end = start + [self.numberArr[i] floatValue] * 2 * M_PI;

        //添加一个子layer用于判断是否在范围内
        CAShapeLayer *subLayer = [CAShapeLayer layer];
        subLayer.strokeColor = [UIColor clearColor].CGColor;
        subLayer.fillColor = [UIColor clearColor].CGColor;
        CGPoint center = CGPointMake(CGRectGetMidX(bgLayer.bounds), CGRectGetMidY(bgLayer.bounds));

        
        UIBezierPath *subPath = [UIBezierPath bezierPath];
        [subPath moveToPoint:center];
        [subPath addArcWithCenter:center radius:self.radius startAngle:start endAngle:end clockwise:YES];
        subLayer.path = subPath.CGPath;
        [bgLayer addSublayer:subLayer];
        
        
        YBKCustomPieLayer *layer = [YBKCustomPieLayer layer];
        layer.lineWidth = self.circleWidth;
        layer.fillColor = [UIColor clearColor].CGColor;
        layer.strokeColor = [self.colorArr[i] CGColor];

        end = start + [self.numberArr[i] floatValue] * 2 * M_PI;

        UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:self.radius - self.circleWidth / 2 startAngle:start endAngle:end clockwise:YES];
        layer.startAngle = start;
        layer.endAngle = end;

        layer.path = path.CGPath;
        [subLayer addSublayer:layer];
        
        start = end;
        
        double middleAngle = (layer.startAngle + layer.endAngle) / 2.0;
        CGPoint newPosition = CGPointMake(bgLayer.position.x + (self.radius + kSpace_PointToPie) * cos(middleAngle), bgLayer.position.y + (self.radius + kSpace_PointToPie) * sin(middleAngle));
        
        //添加指示点
        CAShapeLayer *circlepointLayer = [CAShapeLayer layer];
        UIBezierPath *circlepointPath = [UIBezierPath bezierPathWithArcCenter:newPosition radius:2 startAngle:0 endAngle:M_PI * 2 clockwise:NO];
        circlepointLayer.fillColor = layer.strokeColor;
        circlepointLayer.path = circlepointPath.CGPath;
        [self.layer addSublayer:circlepointLayer];
        //画线
        CAShapeLayer *pointLayer = [CAShapeLayer layer];
        pointLayer.lineCap = kCALineCapRound;
        pointLayer.lineJoin = kCALineJoinRound;
        UIBezierPath *pointPath = [UIBezierPath bezierPath];
        [pointPath moveToPoint:newPosition];
        CGPoint firstLinePoint = CGPointMake(0, 0);
        if (newPosition.x >= bgLayer.position.x) {
            if (newPosition.y >= bgLayer.position.y) {
                //第一象限
                firstLinePoint = CGPointMake(newPosition.x + kSpace_LineTurning * cos(M_PI_4 / 2), newPosition.y + kSpace_LineTurning * sin(M_PI_4 * 7 / 8));
                
            } else {
                //第四象限
                firstLinePoint = CGPointMake(newPosition.x + kSpace_LineTurning * cos(M_PI_2 * 3 + M_PI_4), newPosition.y + kSpace_LineTurning * sin(M_PI_2 * 3 + M_PI_4));
            }
        } else {
            if (newPosition.y >= bgLayer.position.y) {
                //第二象限
                firstLinePoint = CGPointMake(newPosition.x + kSpace_LineTurning * cos(M_PI - M_PI_4), newPosition.y + kSpace_LineTurning * sin(M_PI - M_PI_4));
            } else {
                //第三象限
                firstLinePoint = CGPointMake(newPosition.x + kSpace_LineTurning * cos(M_PI + M_PI_4), newPosition.y + kSpace_LineTurning * sin(M_PI + M_PI_4));
            }
        }        [pointPath addLineToPoint:firstLinePoint];
        CGFloat x = firstLinePoint.x > bgLayer.position.x ? 40:-40;

        CGPoint secondLinePoint = CGPointMake(firstLinePoint.x + x, firstLinePoint.y);
        [pointPath addLineToPoint:secondLinePoint];

        
        pointLayer.strokeColor = layer.strokeColor;
        pointLayer.fillColor = [UIColor clearColor].CGColor;
        pointLayer.lineWidth = 1;
        pointLayer.path = pointPath.CGPath;
        [self.layer addSublayer: pointLayer];
        
        //添加文字
        NSString *number = [NSString stringWithFormat:@" %.f%% ", [self.numberArr[i] floatValue] * 100];
        NSString *city = [NSString stringWithFormat:@" %@ ", self.titleArr[i]];
        NSDictionary *texttr = @{NSFontAttributeName:[UIFont systemFontOfSize:10], NSForegroundColorAttributeName:[UIColor lightGrayColor]};

        CGSize numberSize = [number sizeWithAttributes:texttr];;
        [self addTextLayerWithText:number Frame:CGRectMake(secondLinePoint.x - numberSize.width / 2, secondLinePoint.y - numberSize.height, numberSize.width, numberSize.height) FontSize:10];
        CGSize citySize = [city sizeWithAttributes:texttr];;
        [self addTextLayerWithText:city Frame:CGRectMake(secondLinePoint.x - citySize.width / 2, secondLinePoint.y, citySize.width, citySize.height) FontSize:10];
    }
}

添加文字textLayer

- (void)addTextLayerWithText:(NSString *)text Frame:(CGRect)frame FontSize:(CGFloat)fontSize {
    CATextLayer *textLayer = [CATextLayer layer];
    textLayer.string = text;
    textLayer.alignmentMode = kCAAlignmentCenter;
    textLayer.fontSize = fontSize;
    textLayer.foregroundColor = [UIColor lightGrayColor].CGColor;
    textLayer.frame = frame;
    textLayer.contentsScale = [UIScreen mainScreen].scale;
    textLayer.wrapped = NO;
    [self.layer addSublayer:textLayer];
}

最后再添加一个点击效果在touchesBegan中判断点击的是饼图还是view。如果点击的是view,那么maskLayer遮罩动画显示出来;如果点击的是饼图,那么饼图中对应的块就凸显出来:

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    CGPoint point = [touches.anyObject locationInView:self];
    CGPoint newPoint = [bgLayer convertPoint:point fromLayer:self.layer];

    
    if (![bgLayer containsPoint:newPoint]) {
        [self stroke];
        return;
    }

    for (CAShapeLayer *tmpLayer in bgLayer.sublayers) {
        //判断是否在透明层
        YBKCustomPieLayer *pieLayer = (YBKCustomPieLayer *)tmpLayer.sublayers.firstObject;
        if (CGPathContainsPoint(tmpLayer.path, &CGAffineTransformIdentity, newPoint, 0) && !pieLayer.isSelected) {
            pieLayer.isSelected = YES;
            CGPoint position = pieLayer.position;
            double middleAngle = (pieLayer.startAngle + pieLayer.endAngle) / 2.0;
            CGPoint newPosition = CGPointMake(position.x + kSpace_PointToPie * cos(middleAngle), position.y + kSpace_PointToPie * sin(middleAngle));
            pieLayer.position = newPosition;

        } else {
            pieLayer.position = CGPointMake(0, 0);
            pieLayer.isSelected = NO;
        }
    }
}

maskLayer遮罩的动画代码

- (void)stroke{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    animation.duration = 1.f;
    animation.fromValue = [NSNumber numberWithFloat:1.f];
    animation.toValue = [NSNumber numberWithFloat:0.f];
    //禁止还原
    animation.autoreverses = NO;
    //禁止完成即移除
    animation.removedOnCompletion = NO;
    //让动画保持在最后状态
    animation.fillMode = kCAFillModeForwards;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [maskLayer addAnimation:animation forKey:@"strokeEnd"];
}

代码部分至此结束,下面是调用代码,5s后重设dataArr,并刷新UI。有一个bug还没有优化,就是重设dataArr后,数据较多,文字部分有重叠

    NSArray *dataArr = @[@{@"number":@"0.15", @"city":@"郑州"}, @{@"number":@"0.3", @"city":@"上海"}, @{@"number":@"0.1", @"city":@"苏州"}, @{@"number":@"0.05", @"city":@"无锡"}, @{@"number":@"0.2", @"city":@"成都"}];
    YBKCustomPieView *pieView = [[YBKCustomPieView alloc] initWithFrame:CGRectMake(0, kHeight_Screen / 2 - 150, kWidth_Screen , 300) WithRadius:60 CircleWidth:50 DataArr:dataArr];
    [self.view addSubview:pieView];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSArray *dataArr = @[@{@"number":@"0.15", @"city":@"郑州"}, @{@"number":@"0.23", @"city":@"上海"}, @{@"number":@"0.1", @"city":@"苏州"}, @{@"number":@"0.05", @"city":@"无锡"}, @{@"number":@"0.2", @"city":@"成都"}, @{@"number":@"0.2", @"city":@"北京"}, @{@"number":@"0.01", @"city":@"南京"}, @{@"number":@"0.03", @"city":@"厦门"}];
        pieView.dataArr = dataArr;
        [pieView setNeedsDisplay];
    });

备注:基本没写啥注释,如果有需要,请跳转原博客:https://www.jianshu.com/p/97570c6cafa0

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