CAShapeLayer+UIBezierPath實現(xiàn)折線圖

先看看效果圖

折線.gif
一個很簡單的折線圖效果,使用的CAShapeLayer+UIBezierPath
CAShapeLayer和CALayer比較:
  • #######drawRect:屬于CoreGraphics框架,占用CPU,性能消耗大
  • #######CAShapeLayer:屬于CoreAnimation框架,通過GPU來渲染圖形,節(jié)省性能。動畫渲染直接提交給手機GPU,不消耗內存

實現(xiàn)思路:

  1. 橘色空心的圓圈,我用的是view來實現(xiàn)的
  2. 灰色的豎線用的是view 然后添加了一個CAGradientLayer的圖層做到顏色漸變(這個我會在下一篇寫使用CAGradientLayer的例子)
  3. 劃線就是用UIbezierPath
  4. 使用for循環(huán),計算好距離,然后微調一下距離就可以了

代碼部分

  • 在這里,我的折線圖是根據(jù)統(tǒng)計 一周 或者 一月 內的駕駛里程時間,所以需要提供三組數(shù)據(jù),在這里來一個周的:

     // 測試數(shù)據(jù) 28 29 30 1 2 3 4 號
     @property(nonatomic,strong)NSMutableArray *numbers;
     //測試數(shù)據(jù) 里程數(shù)組
     @property(nonatomic,strong)NSMutableArray *kmArr;
     //測試數(shù)據(jù) 時間數(shù)組(這個順序,)
     @property(nonatomic,strong)NSMutableArray *timeArr;
    
  • 我用來顯示折線圖的View是foldLineView,所以你在控制器創(chuàng)建一個foldLineView,然后給他設定大小,我的Demo給定的大小:
    //左右間隔15,然后高度給定
    self.foldLineView = [[FoldLineView alloc]initWithFrame:CGRectMake(15, 100, [UIScreen mainScreen].bounds.size.width - 30, 200)];

  • 接下來就是內部實現(xiàn):
    #import "FoldLineView.h"
    #import "Masonry.h"

    @interface FoldLineView ()
    
    //坐標點數(shù)組
    @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;
     }
    //時間數(shù)組是最后一個賦值的,所以等他賦值之后有了數(shù)據(jù)就可以進行操作(當然,邏輯就是等所有的數(shù)據(jù)到手后開始畫Layer)
    -(void)setTimeArr:(NSMutableArray *)timeArr{
        _timeArr = timeArr;
        [self setUI];
    }
    -(void)setUI{
      //每個日期之間的間距 -- (我的設計中,一個頁面只能展示7個數(shù)據(jù),根據(jù)這一點,可以計算出點之間的間距)
     //這里的60,是指第一個點和最后一個點,距離view的距離和是60,也就是左右間距30
        CGFloat space = (self.bounds.size.width - 60) / (7- 1) ;
    //    NSLog(@"%f",space);
    

//for循環(huán)添加下面的日期數(shù)字,根據(jù)間距
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];
}
//找最大里程數(shù)
//這個地方的邏輯是: 找到這組數(shù)據(jù)中的最大值,然后根據(jù)最大值,選擇一個合適的數(shù)值當做最大值,然后根據(jù)數(shù)組里的值等比例安排各個點的位置
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;
//求出坐標點在線上的比例,然后添加到數(shù)組
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);
   }

  //根據(jù)點劃線
  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]))];
    }
  }
  //在這里創(chuàng)建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,用來表示展示程度, 數(shù)值在0-1之間,我先全部設置0,因為要添加動畫
  self.shapeLayer.strokeStart = 0;
  self.shapeLayer.strokeEnd = 0;
  [self.layer addSublayer:self.shapeLayer];
  //將定時器 手動添加運行循環(huán),防止滑動時候動畫停止
  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];
  //先畫線,在添加點,這樣用點來擋住線頭
  //根據(jù)坐標繪制點
  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,就可以實現(xiàn)動畫效果
  if (self.shapeLayer.strokeEnd < 1.0) {
     //自己微調的add數(shù)值,看起來能平緩點的劃線
    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

老規(guī)矩---gitHub地址:https://github.com/superHS/FoldLineView.git

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容