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
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容