iOS 如何绘制饼状图

作者: 大大盆子 | 来源:发表于2017-05-04 16:40 被阅读2747次

先来见识一下史上最无力的背打



OK!进入正题,哈哈😀

前言

对于图形的绘制,我们可以用CoreGraphics中CGContext或者UIKit中UIBezierPath,前者是一个C语言类,功能强大,后者是基于前者封装的OC类,使用起来更方便,两者都可以在View的drawRect中直接绘制出想要的图形。但是我们这里为了后续操作方便,每个path都使用一个承载对象,CALayer跟CAShapeLayer都可以,显然后者更专业,专注形状绘制,那么就它了😀

主要对象及属性

  • UIBezierPath,之前专门写了一篇对 UIBezierPath的理解与运用,这里我就不再说了。

  • CAShapeLayer,专注绘制形状的图层,继承自CALayer,拥有CALayer所有特性,且增加了一些特有的属性。

      //路径,根据这个路径来绘制形状
      @property(nullable) CGPathRef path;
      //路径所包含区域的填充色
      @property(nullable) CGColorRef fillColor;
      //绘制路径的颜色
      @property(nullable) CGColorRef strokeColor;
      //路径绘制的开始值,默认为0,可以更改这个值来控制路径绘制的起始位置
      @property CGFloat strokeStart;
      //路径绘制的结束值,默认为1,可以更改这个值来控制路径绘制的结束位置
      @property CGFloat strokeEnd;
      //线宽
      @property CGFloat lineWidth;
    

怎么做?

要绘制一个饼状图,首先我们要了解饼状图的结构,我们前面提到过,可以直接在drawRect通过UIBezierPath拼接来画出一个饼状图,但是每个path没有单独的承载对象,不方便交互,所以才用CAShapeLayer,那么一个饼状图就是一个一个的CAShapeLayer按照顺序排列组合起来的,所以关键就在排列组合上面,下面提供两种思路:

  1. 所有CAShapeLayer共用一个圆形的UIBezierPath,然后通过设置每一个CAShapeLayer的strokeStartstrokeEnd属性来控制该layer在这个Path中所在的位置,这样就能轻松画出一个饼状图了。接下来我们就需要计算每一个CAShapeLayer的strokeStartstrokeEnd,当我们拿到数据源的时候,先对数据进行排序处理,然后遍历数组,将strokeStartstrokeEnd收尾相接即可,废话有点多,直接上代码:

    - (void)setDatas:(NSArray <NSNumber *>*)datas
              colors:(NSArray <UIColor *>*)colors{
         NSArray *newDatas = [self getPersentArraysWithDataArray:datas];
         CGFloat start = 0.f;
         CGFloat end = 0.f;
         UIBezierPath *piePath = [UIBezierPath bezierPathWithArcCenter:_center radius:_radius + Hollow_Circle_Radius startAngle:-M_PI_2 endAngle:M_PI_2*3 clockwise:YES];
         
         for (int i = 0; i < newDatas.count; i ++) {                
             NSNumber *number = newDatas[i];
             end =  start + number.floatValue;
             CAShapeLayer *pieLayer = [CAShapeLayer layer];
             pieLayer.strokeStart = start;
             pieLayer.strokeEnd = end;
             pieLayer.lineWidth = _radius*2 - Hollow_Circle_Radius;
             pieLayer.strokeColor = [colors.count > i?colors[i]:kPieRandColor CGColor];
             pieLayer.fillColor = [UIColor clearColor].CGColor;
             pieLayer.path = piePath.CGPath;
              
             [self.layer addSublayer:pieLayer];
             start = end;
         }
    }
    

    数据处理:

    /**
     将数据按降序排列,再计算出所占比例返回
    
     @param datas 原始数据
     @return 数据占比数组
    */
    - (NSArray *)getPersentArraysWithDataArray:(NSArray *)datas{
         NSArray *newDatas = [datas sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
             if ([obj1 floatValue] < [obj2 floatValue]) {
                 return NSOrderedDescending;
             }else if ([obj1 floatValue] > [obj2 floatValue]){
                 return NSOrderedAscending;
             }else{
                 return NSOrderedSame;
             }
         }];
    
         NSMutableArray *persentArray = [NSMutableArray array];
         NSNumber *sum = [newDatas valueForKeyPath:@"@sum.floatValue"];
         for (NSNumber *number in newDatas) {
             [persentArray addObject:@(number.floatValue/sum.floatValue)];
         }
    
        return persentArray;
    }
    
  2. 每个CAShapeLayer对应一个单独的UIBezierPath,我比较推荐使用这一种方式,因为在处理点击事件的时候,这种方式就可以判断point是否是在path内部,从而找到对应的layer,而第一种方式因为所有layer共用的一个UIBezierPath,以致于无法识别点击的point是属于哪一个layer,下面再看代码:

    - (void)setDatas:(NSArray <NSNumber *>*)datas
           colors:(NSArray <UIColor *>*)colors{
     
        NSArray *newDatas = [self getPersentArraysWithDataArray:datas];
        CGFloat start = -M_PI_2;
        CGFloat end = start;
        //之所以加上这个循环,也是考虑到如果多次调用,也不会重复创建layer
        while (newDatas.count > self.layer.sublayers.count) {
           XZMLayer *pieLayer = [XZMLayer layer];
           pieLayer.strokeColor = NULL;
           [self.layer addSublayer:pieLayer];
        }
     
        for (int i = 0; i < self.layer.sublayers.count; i ++) {
         
            XZMLayer *pieLayer = (XZMLayer *)self.layer.sublayers[i];
            if (i < newDatas.count) {
               pieLayer.hidden = NO;
               end =  start + M_PI*2*[newDatas[i] floatValue];
             
               UIBezierPath *piePath = [UIBezierPath bezierPath];
               [piePath moveToPoint:_center];
               [piePath addArcWithCenter:_center radius:_radius*2 startAngle:start endAngle:end clockwise:YES];
             
               pieLayer.fillColor = [colors.count > i?colors[i]:kPieRandColor CGColor];
               pieLayer.startAngle = start;
               pieLayer.endAngle = end;
               pieLayer.path = piePath.CGPath;
             
               start = end;
           }else{
               pieLayer.hidden = YES;
           }
       }
    }
    

    定义一个XZMLayer出来,也是为了方便我们添加属性

    @interface XZMLayer : CAShapeLayer
    
    @property (nonatomic,assign)CGFloat startAngle; //开始角度
    @property (nonatomic,assign)CGFloat endAngle;   //结束角度
    @property (nonatomic,assign)BOOL    isSelected; //是否已经选中
    
    @end
    

至此,我们的饼状图就基本已经画出来了,下面贴一张Demo图片


这个图太死板了,我们给它来点活力,添加动画!

添加动画

乍一看感觉不知从何下手,其实很简单!就是通过一个mask属性来控制显示区域,mask可以理解成一个背景层,当我们自定义一个mask的layer,layer默认是透明的,即背景是透明的,所以什么都看不到,当给mask赋值一个非透明任意背景颜色,则表现层的东西才能展示出来,所以我们只要通过给mask加一个绘制动画就可以了。

创建一个layer作为整个view.layer.mask

//通过mask来控制显示区域
_maskLayer = [CAShapeLayer layer];
UIBezierPath *maskPath = [UIBezierPath bezierPathWithArcCenter:_center radius:self.bounds.size.width/4.f startAngle:-M_PI_2 endAngle:M_PI_2*3 clockwise:YES];
//设置边框颜色为不透明,则可以通过边框的绘制来显示整个view
 _maskLayer.strokeColor = [UIColor greenColor].CGColor;
 _maskLayer.lineWidth = self.bounds.size.width/2.f;
 //设置填充颜色为透明,可以通过设置半径来设置中心透明范围
 _maskLayer.fillColor = [UIColor clearColor].CGColor;
 _maskLayer.path = maskPath.CGPath;
 _maskLayer.strokeEnd = 0;
 self.layer.mask = _maskLayer;

给这个maskLayer添加一个基础动画

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

来看看效果


交互

交互主要体现在用户点击上面,表现形式有很多种,具体根据需求来定,这里我来讲一下用户点击进行单元拆分的这么一个功能。首先我们要确定触摸的point是在哪一个模块,拿到这个模块之后再来拆分,也就是更改layer的position(中心点)属性值,默认是(0,0),而拆分的方向是沿着一条过圆心以及layer的position的直线往外的方向,在设定偏移量之后,根据三角函数可以轻松求出新的position(x,y),说起来有点绕口,来画个图就清楚了😀


这图画的我自己都怕😀,图上绿色的就是设定的偏移值,我们只要求出(x,y)就可以了,很简单吧,一个直角三角形,已知斜边跟角度,求另外两边长,三角函数啊,初中就学过的吧,哈哈!不废话了,上代码

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    CGPoint point = [touches.anyObject locationInView:self];
    
    [self upDateLayersWithPoint:point];
    
}

- (void)upDateLayersWithPoint:(CGPoint)point{
    //遍历查找点击的是哪一个layer
    for (XZMLayer *layer in self.layer.sublayers) {

        if (CGPathContainsPoint(layer.path, &CGAffineTransformIdentity, point, 0) && !layer.isSelected) {
            layer.isSelected = YES;

            //原始中心点为(0,0),扇形所在圆心、原始中心点、偏移点三者是在一条直线,通过三角函数即可得到偏移点的对应x,y。
            CGPoint currPos = layer.position;
            double middleAngle = (layer.startAngle + layer.endAngle)/2.0;
            CGPoint newPos = CGPointMake(currPos.x + KOffsetRadius*cos(middleAngle), currPos.y + KOffsetRadius*sin(middleAngle));
            layer.position = newPos;
            
        }else{

            layer.position = CGPointMake(0, 0);
            layer.isSelected = NO;
        }
    }
}

再来看效果


注意

  • CAShapeLayer的lineWidth会影响整个path的大小,因为lineWidth是从边界往内外两边延伸的,比如lineWidth设置为10,那么就会往外扩大5,所以在设置半径的时候需要把线宽考虑进来。
  • Demo在此,看到了就顺手点个赞呗!😀

相关文章

  • iOS 如何绘制饼状图

    先来见识一下史上最无力的背打 前言 对于图形的绘制,我们可以用CoreGraphics中CGContext或者UI...

  • iOS CGContextRef

    一、绘制饼状图 饼状图的简单实现代码:

  • iOS绘制饼状图

    效果图 1 创建SKPPieChartView继承于UIView 2 SKPPieChartView.h 3 SK...

  • iOS使用Charts框架绘制—饼状图

    iOS使用Charts框架绘制—饼状图[https://www.jianshu.com/p/45194d861b21]

  • Swift第三方Charts的简单使用

    Charts是一个强大的图表框架,MPAndroidChart 在 iOS 上的移植。可以绘制线形图,直方图,饼状...

  • charts3

    先进行charts饼状图的小测,如下,结果为正常饼状图 绘制前面数据库中的数据来找某一天交易的各类目物品的饼状图 ...

  • IOS开发之——绘制饼状图

    文章搬运来源:https://blog.csdn.net/Calvin_zhou/article/details/...

  • matplotlib绘制图表

    python中使用matplotlib库可以快速画简单的图表下面介绍下柱状图和饼图绘制1 柱状图绘制 2 饼状图绘...

  • 学习笔记----python绘图pie

    # python 绘制饼状图 #-*- coding:utf-8 –*- import matplotlib.py...

  • Android 绘制饼状图

    工作中有绘制饼状图功能,自己稍微修改了一下前边人的写作方法。 1.具体是一个空心的圆环外层是两种颜色的扇形图的一部...

网友评论

  • 了无羁绊:大神牛逼啊
  • fd565ceeb15b:@大大盆子
    你好 我想在两个扇形之间添加一个间距,该如何实现,谢谢
    fd565ceeb15b:@大大盆子 我试了,也调了一会不行,因为添加间距后,所有的扇形的圆心就会改变。相当于整体向外拉,。
    fd565ceeb15b:@大大盆子 我明天试试,多谢:pray:
    大大盆子:定义一个间距为space,在那个循环里面,把M_PI*2改成(M_PI*2-space * (newDatas.count - 1) ) ,再改start = end + space,目测是这样的 你可以去试试
  • 灯红酒绿映不出的落寞:给了很大的启发。谢谢。明天试试。
    大大盆子:@灯红酒绿映不出的落寞 不客气,一起进步!
  • 冰三尺:为甚我做的动画是只有边框的动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    这句代码是对边框做的动画, 怎么变成对整个圆动画了呢?
    大大盆子:@里脊糖醋 边框的宽度就是圆的半径,所以看起来就是整个圆在做动画
  • Orz__::clap: 666,很强势

本文标题:iOS 如何绘制饼状图

本文链接:https://www.haomeiwen.com/subject/xcrozttx.html