iOS 画个简单的饼图

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


iOS 画个简单的饼图_第1张图片
pie_pic1.jpg
iOS 画个简单的饼图_第2张图片
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) {
            self.circleWidth = radius;
        }
        self.dataArr = dataArr;
    }
    return self;
}

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

-(void)setDataArr:(NSArray *)dataArr { 
    CGFloat sumValue = [[dataArr valueForKeyPath:@"[email protected]"] 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 *)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

你可能感兴趣的:(iOS 画个简单的饼图)