iOS开发之环形进度条加载动画实现

最近在开发的时候遇到一个需求,就是产品要求实现环形进度条显示进度的时候加载一个进度的效果。环形进度条的实现比较简单,代码如下:

CGContextRef ctx = UIGraphicsGetCurrentContext();//获取上下文

    CGPoint center = self.center;
    CGFloat radius = self.progressRadius;               //设置半径
    CGFloat startA = - M_PI_2;                          //圆起点位置
    CGFloat endA = -M_PI_2 + M_PI * 2 * self.progress;  //圆终点位置
    if (self.progressBgColor) {
        CGFloat bgEndA = -M_PI_2 + M_PI * 2 * 1.0;  //圆终点位置
        UIBezierPath *bgPath = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:bgEndA clockwise:YES];
        bgPath.lineCapStyle = kCGLineCapRound;          //指定线的边缘是圆的
        CGContextSetLineWidth(ctx, self.progressWidth); //设置线条宽度
        [self.progressBgColor setStroke];               //设置描边颜色
        CGContextAddPath(ctx, bgPath.CGPath);           //把路径添加到上下文
        CGContextStrokePath(ctx);                       //渲染

    }


    self.progressLayer.frame = self.bounds;//CAShapeLayer
    self.progressLayer.strokeColor = self.progressColor.CGColor; //指定path的渲染颜色,这里可以设置任意不透明颜色
    self.progressLayer.lineCap = kCALineCapRound;//指定线的边缘是圆的
    self.progressLayer.lineWidth = self.progressWidth;//线的宽度
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
    self.progressLayer.path =[path CGPath];

接下来该整理,加载动画效果了,通过搜索从网上看到,有的小伙伴用NSTimer来实现了相关的加载动画效果,但是NSTimer实现的动画效果多多少少有些卡顿不够平滑,自己感到不够满意。有没有更好的方法呢,通过搜索发现了CAShapeLayer有一个属性叫做strokeEnd可以通过这个属性动画来实现,具体代码如下:


// 为曲线添加轨迹动画
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
animation.fromValue = @0;
animation.toValue = @1;
animation.duration = 1;
animation.removedOnCompletion = YES;
[self.progressLayer addAnimation:animation forKey:nil];

给自己留个备份,嘿嘿。
更多优质文章,可以微信扫码关注:
这里写图片描述

参考博客如下:
https://blog.csdn.net/yixiangboy/article/details/50662704

猜你喜欢

转载自blog.csdn.net/hhl110120/article/details/81266226