iOS利用UIBezierPath绘制折线图

有时候我们需要显示一些数据的变化, 可以用贝塞尔曲线绘制

//绘制线路
- (void)drawPathWithPoints:(NSArray *)points
{
    UIBezierPath *path = [UIBezierPath bezierPath];
    for (int i = 0; i < points.count; i ++) {
        if (i == 0) {
            [path moveToPoint:[points[0] CGPointValue]];
        }else {
            [path addLineToPoint:[points[i] CGPointValue]];
        }
    }
    
    //layer
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.lineWidth = 1;
    layer.fillColor = [UIColor clearColor].CGColor;
    layer.strokeColor = [UIColor blackColor].CGColor;
    layer.path = path.CGPath;
    [self.view.layer addSublayer:layer];
    
    //animation
    CABasicAnimation *basicAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    basicAnimation.fromValue = @(0);
    basicAnimation.toValue = @(1);
    basicAnimation.duration = 1;
    basicAnimation.repeatCount = MAXFLOAT;
    [layer addAnimation:basicAnimation forKey:@"123"];
}

调用以及初始化

- (void)viewDidLoad {
    [super viewDidLoad];
    NSMutableArray *arr = [NSMutableArray array];
    //随机生成几个点
    for (int i = 0 ; i < 10; i ++) {
        int a = CGRectGetWidth([UIScreen mainScreen].bounds) / 10 * i + arc4random() % 30;
        int b;
        if (i % 2 == 0) {
            b = CGRectGetHeight([UIScreen mainScreen].bounds) / 2.0 + arc4random() % 200;
        }else {
            b = CGRectGetHeight([UIScreen mainScreen].bounds) / 2.0 - arc4random() % 200;
        }
        CGPoint p1 = CGPointMake(a, b);
        NSValue *v1 = [NSValue valueWithCGPoint:p1];
        [arr addObject:v1];
    }
    [self drawPathWithPoints:arr];
}

效果

1.gif

你可能感兴趣的:(iOS利用UIBezierPath绘制折线图)