美文网首页iOS动画iOS专题资源__UI专题关注
CAShapeLayer+UIBezierPath实现折线图

CAShapeLayer+UIBezierPath实现折线图

作者: 马路的尽头的大树旁有个小卖铺 | 来源:发表于2016-09-27 21:47 被阅读711次

    先看看效果图

    折线.gif
    一个很简单的折线图效果,使用的CAShapeLayer+UIBezierPath
    CAShapeLayer和CALayer比较:
    • #######drawRect:属于CoreGraphics框架,占用CPU,性能消耗大
    • #######CAShapeLayer:属于CoreAnimation框架,通过GPU来渲染图形,节省性能。动画渲染直接提交给手机GPU,不消耗内存

    实现思路:

    1. 橘色空心的圆圈,我用的是view来实现的
    2. 灰色的竖线用的是view 然后添加了一个CAGradientLayer的图层做到颜色渐变(这个我会在下一篇写使用CAGradientLayer的例子)
    3. 划线就是用UIbezierPath
    4. 使用for循环,计算好距离,然后微调一下距离就可以了

    代码部分

    • 在这里,我的折线图是根据统计 一周 或者 一月 内的驾驶里程时间,所以需要提供三组数据,在这里来一个周的:

       // 测试数据 28 29 30 1 2 3 4 号
       @property(nonatomic,strong)NSMutableArray *numbers;
       //测试数据 里程数组
       @property(nonatomic,strong)NSMutableArray *kmArr;
       //测试数据 时间数组(这个顺序,)
       @property(nonatomic,strong)NSMutableArray *timeArr;
      
    • 我用来显示折线图的View是foldLineView,所以你在控制器创建一个foldLineView,然后给他设定大小,我的Demo给定的大小:
      //左右间隔15,然后高度给定
      self.foldLineView = [[FoldLineView alloc]initWithFrame:CGRectMake(15, 100, [UIScreen mainScreen].bounds.size.width - 30, 200)];

    • 接下来就是内部实现:
      #import "FoldLineView.h"
      #import "Masonry.h"

      @interface FoldLineView ()
      
      //坐标点数组
      @property(nonatomic,strong)NSMutableArray *pointArr;
      //定时器
      @property(nonatomic,strong)NSTimer *timer;
      
      @property(nonatomic,strong)CAShapeLayer *shapeLayer;
      @end
      
      @implementation FoldLineView
      
      -(instancetype)initWithFrame:(CGRect)frame{
           if (self == [super initWithFrame:frame]) {
      
        self.backgroundColor = [UIColor whiteColor];
        }
          return self;
       }
      //时间数组是最后一个赋值的,所以等他赋值之后有了数据就可以进行操作(当然,逻辑就是等所有的数据到手后开始画Layer)
      -(void)setTimeArr:(NSMutableArray *)timeArr{
          _timeArr = timeArr;
          [self setUI];
      }
      -(void)setUI{
        //每个日期之间的间距 -- (我的设计中,一个页面只能展示7个数据,根据这一点,可以计算出点之间的间距)
       //这里的60,是指第一个点和最后一个点,距离view的距离和是60,也就是左右间距30
          CGFloat space = (self.bounds.size.width - 60) / (7- 1) ;
      //    NSLog(@"%f",space);
      

    //for循环添加下面的日期数字,根据间距
    for (int i = 0; i< self.numbers.count; i++ ) {
    UILabel *numberLabel = [[UILabel alloc]initWithFrame:CGRectMake(20 + i * space, 180, 20, 20)];
    numberLabel.text = self.numbers[i];
    numberLabel.font = [UIFont systemFontOfSize:16];
    numberLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:numberLabel];
    }
    //找最大里程数
    //这个地方的逻辑是: 找到这组数据中的最大值,然后根据最大值,选择一个合适的数值当做最大值,然后根据数组里的值等比例安排各个点的位置
    double maxKM = [self.kmArr[0] doubleValue];
    for (int i = 0 ; i < self.numbers.count - 1; i++ ) {
    if (maxKM < [self.kmArr[i]doubleValue]) {
    maxKM = [self.kmArr[i] doubleValue];
    }
    }
    //最大里程设置为高度90% 求出最大值
    maxKM = maxKM / 0.9;
    //求出坐标点在线上的比例,然后添加到数组
    self.pointArr = [NSMutableArray array];
    for (int i = 0; i< self.numbers.count; i++ ) {
    [self.pointArr addObject:[NSString stringWithFormat:@"%f",[self.kmArr[i] doubleValue] /maxKM]];
    }
    //NSLog(@"%@",self.pointArr);

      //添加七根线
      for (int i = 0; i< self.numbers.count; i++ ) {
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(20 + i * space + 9, 0, 1, 180)];
        [self addSubview:lineView];
        //给线添加渐变
        CAGradientLayer *lineLayer = [CAGradientLayer layer];
        lineLayer.frame = lineView.bounds;
        [lineView.layer addSublayer:lineLayer];
        //颜色分配
        lineLayer.colors = @[(__bridge id)[UIColor clearColor].CGColor,
                              (__bridge id)[UIColor colorWithRed:221/255.0 green:223/255.0 blue:225/255.0 alpha:0.6f].CGColor,
                              (__bridge id)[UIColor clearColor].CGColor,];
        lineLayer.locations  = @[@(0),@(1)];
        // 起始点
        lineLayer.startPoint = CGPointMake(0.5, 0);
        
        // 结束点
        lineLayer.endPoint   = CGPointMake(0.5,1);
       }
    
      //根据点划线
      UIBezierPath *path = [UIBezierPath bezierPath];
    
      for (int i = 0; i< self.numbers.count; i++ ) {
        //判断,第一个点的时候,先添加点
        if (i == 0 ) {
            //这个地方加9 是因为为了让点在最中间
            [path moveToPoint:CGPointMake(20 + 9, 6 + 170 * (1 - [self.pointArr[0]  doubleValue]))];
        }else{
            [path addLineToPoint:CGPointMake(20 + space * i + 9,6 + 170 * (1 - [self.pointArr[i] doubleValue]))];
        }
      }
      //在这里创建CAShapeLayer
      self.shapeLayer = [[CAShapeLayer alloc]init];
      //设置CAShapeLayer的frame
      self.shapeLayer.frame = self.bounds;
      //设置填充颜色--因为是线,所以不需要.clearColor就行
      self.shapeLayer.fillColor = [UIColor clearColor].CGColor;
      //设置线的颜色
      self.shapeLayer.strokeColor = [UIColor orangeColor].CGColor;
      //设置线宽
      self.shapeLayer.lineWidth = 1.f;
      //把UIBezierPath给CAShapeLayer
      self.shapeLayer.path = path.CGPath;
      //设置stroke,用来表示展示程度, 数值在0-1之间,我先全部设置0,因为要添加动画
      self.shapeLayer.strokeStart = 0;
      self.shapeLayer.strokeEnd = 0;
      [self.layer addSublayer:self.shapeLayer];
      //将定时器 手动添加运行循环,防止滑动时候动画停止
      self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(add) userInfo:nil repeats:YES];
      NSRunLoop *currentRunLoop = [NSRunLoop currentRunLoop];
      [currentRunLoop addTimer:self.timer forMode:NSRunLoopCommonModes];
      //先画线,在添加点,这样用点来挡住线头
      //根据坐标绘制点
      for (int i = 0; i< self.numbers.count; i++ ) {
        
        CGFloat point = [self.pointArr[i] doubleValue];
        //        NSLog(@"%f",point);
        UIView *pointView = [[UIView alloc]initWithFrame:CGRectMake(20 + i * space + 4, 170 * (1 - point ), 12, 12)];
    
        //设置成白色,可以挡住线头
        pointView.backgroundColor = [UIColor whiteColor];
        pointView.layer.borderWidth = 2;
        pointView.layer.borderColor = [UIColor orangeColor].CGColor;
        pointView.layer.cornerRadius = 6;
        pointView.layer.masksToBounds = YES;
        [self addSubview:pointView];
        
        //添加标签
        UILabel *textLabel = [[UILabel alloc]init];
        textLabel.font = [UIFont systemFontOfSize:10];
        textLabel.textColor = [UIColor lightGrayColor];
        textLabel.text = [NSString stringWithFormat:@"%@/%@",self.kmArr[i],self.timeArr[i]];
        [textLabel sizeToFit];
        [self addSubview:textLabel];
        //这里我使用了masonry做约束
        [textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(pointView.mas_top).offset(- 5);
            make.centerX.mas_equalTo(pointView.mas_centerX);
        }];
      }
      }
      //做动画
      -(void)add{
      //一点点的添加strokeEnd,就可以实现动画效果
      if (self.shapeLayer.strokeEnd < 1.0) {
         //自己微调的add数值,看起来能平缓点的划线
        CGFloat add = 1.0 / (self.numbers.count + 3);
        NSLog(@"add-->>%f",add);
        self.shapeLayer.strokeEnd += add;
        NSLog(@"%f",self.shapeLayer.strokeEnd);
      }else{
        //取消定时器
        [self.timer invalidate];
        self.timer = nil;
      }
    
      }
    
      @end
    

    上面的案例我做了一个view和刻滚动的scrollView

    老规矩---gitHub地址:https://github.com/superHS/FoldLineView.git

    相关文章

      网友评论

      本文标题:CAShapeLayer+UIBezierPath实现折线图

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