美文网首页
使用UIBezierPath画圆形进度条

使用UIBezierPath画圆形进度条

作者: 枫叶风 | 来源:发表于2018-06-28 12:25 被阅读0次
    最终效果图

    CAShapeLayer

    CAShapeLayer继承自CALayer,根据贝塞尔曲线的路径,可以绘制出各种形状的图形。简单的说,UIBezierPath制定出绘制的路径,然后CAShapeLayer根据指定的路径绘制出相应的形状。

    代码

    画贝塞尔曲线最主要的就是startAngleendAngle两个属性,根据下图标注可以按照需要来选择角度。

    要做出进度条的样式,首先画两个圆,一个作为底部灰色的,另一个是前面进度条圆弧:

        CAShapeLayer *frontCircle = [CAShapeLayer layer];  // 进度条圆弧
        CAShapeLayer *backCircle = [CAShapeLayer layer]; //进度条底
        [self.circleView.layer addSublayer:backCircle];
        [self.circleView.layer addSublayer:frontCircle];
        
        // 画底
        UIBezierPath *backPath = [UIBezierPath bezierPathWithArcCenter:self.circleView.center radius:100 startAngle:0 endAngle:M_PI*2 clockwise:YES];
        backCircle.lineWidth = 12;  // 线条宽度
        backCircle.strokeColor = [[UIColor grayColor] CGColor]; // 边缘线的颜色
        backCircle.fillColor = [[UIColor clearColor] CGColor];  // 闭环填充的颜色
        backCircle.lineCap = @"round";  // 边缘线的类型
        backCircle.path = backPath.CGPath; // 从贝塞尔曲线获取到形状
        
        // 画刻度
        UIBezierPath *frontPath = [UIBezierPath bezierPathWithArcCenter:self.circleView.center radius:100 startAngle:M_PI endAngle:M_PI*2 clockwise:YES];
        frontCircle.lineWidth = 12;
        frontCircle.strokeColor = [[UIColor blueColor] CGColor];
        frontCircle.fillColor = [[UIColor clearColor] CGColor];
        frontCircle.lineCap = @"round";
        frontCircle.path = frontPath.CGPath;
    

    这样一个简单的进度条就出来了


    接下来添加动画效果,使用CABasicAnimation根据CAShapeLayer来显示动画:
        // 动画
        CABasicAnimation *animation = [CABasicAnimation animation];
        animation.keyPath = @"strokeEnd";
        animation.duration = 1; // 动画时长
        animation.fromValue = @0; // 开始值
        frontCircle.strokeEnd = 1;
        // 给layer添加动画
        [frontCircle addAnimation:animation forKey:nil];
    

    最后一步是添加小圆点,小圆点就是一个白色的view并通过动画来改变小圆点的位置:

        // 小圆点
        UIView *roundView = [[UIView alloc] init];
        roundView.frame = CGRectMake(50, 50, 8, 8);
        roundView.layer.masksToBounds = YES;
        roundView.layer.cornerRadius = 4;
        roundView.backgroundColor = [UIColor whiteColor];
        [self.circleView addSubview:roundView];
    
        // 小圆点动画
        CAKeyframeAnimation *animation1 = [CAKeyframeAnimation animationWithKeyPath:@"position"];
        animation1.duration = 1;
        // 小圆点的路径与进度条弧度一样
        animation1.path = frontPath.CGPath;
        animation1.fillMode = kCAFillModeForwards;
        animation1.removedOnCompletion = NO;
        [roundView.layer addAnimation:animation1 forKey: nil];
    

    这样一个简单的圆形进度条就完成了,这里也有demo可以下载:(https://github.com/sunbin117/circleView)

    相关文章

      网友评论

          本文标题:使用UIBezierPath画圆形进度条

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