美文网首页iOS高阶UI相关程序员
UIBezierPath+CAShapeLayer绘制进度环

UIBezierPath+CAShapeLayer绘制进度环

作者: makemake | 来源:发表于2017-10-24 14:52 被阅读44次
    - (instancetype)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];
        if (self) {
    
            [self masLayoutSubview];
        }
        return self;
    }
    

    + (instancetype)bezierPathWithArcCenter:(CGPoint)center radius:(CGFloat)radius startAngle:(CGFloat)startAngle endAngle:(CGFloat)endAngle clockwise:(BOOL)clockwise;
    :(CGPoint)center中心点
    :(CGFloat)radius半径
    :(CGFloat)startAngle起点
    :(CGFloat)endAngle终点
    :(BOOL)clockwise是否顺时针

    - (void)masLayoutSubview{
        
        bottomPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.frame.size.width/2.0, self.frame.size.height/2.0) radius:self.frame.size.width/2.0 - 10 startAngle:- M_PI_2 endAngle:-M_PI_2 + M_PI * 2 clockwise:YES];
    
        CAShapeLayer *bottomLayer = [CAShapeLayer layer];
        bottomLayer.frame = self.bounds;
        bottomLayer.path = bottomPath.CGPath;
        bottomLayer.lineWidth = lineWidth;
        bottomLayer.strokeColor = [UIColor grayColor].CGColor;
        bottomLayer.fillColor = nil;
        [self.layer addSublayer:bottomLayer];
    
        
        layer = [CAShapeLayer layer];
        layer.frame = self.bounds;
        layer.lineWidth = lineWidth;
        layer.fillColor = nil;
        layer.lineCap = kCALineCapRound;
        self.layer.contentsScale = [[UIScreen mainScreen]scale];
        [self.layer addSublayer:layer];
           
        
    }
    

    对外提供设置进度接口:(不用多次addsubLayer,直接修改CAShapeLayer的path路径就可以了)
    CABasicAnimation 看情况是否加

    - (void)setProgress:(CGFloat)value{
        
        path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.frame.size.width/2.0, self.frame.size.height/2.0)  radius:self.frame.size.width/2.0 - 10
                                                        startAngle:3*M_PI_2 endAngle:3*M_PI_2+(2*M_PI*value) clockwise:YES];
    
        layer.path = path.CGPath;
        
    
        
    //    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    //    animation.fromValue = @(0.0);
    //    animation.toValue = @(1.0);
    //    animation.duration = 1.f;
    //    [layer addAnimation:animation forKey:nil];
        
    
    }
    

    效果如下:

    picture.gif

    难点:
    定义圆环的起点为3/2π 也就是3*M_PI_2 ,计算终点的公式为3*M_PI_2+(2*M_PI*value)

    120336-7f77dcb0cc28e0ef.png

    相关文章

      网友评论

        本文标题:UIBezierPath+CAShapeLayer绘制进度环

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