Apply gradient color to arc created with UIBezierPath

前端 未结 3 649
感情败类
感情败类 2020-12-12 16:00

I want to create a progress bar that has the form of an arc. The color of the progress bar has to change according to the values.

I created an arc using UIBez

3条回答
  •  天命终不由人
    2020-12-12 16:09

    You can use a CAGradientLayer to get the gradient effect, and use the CAShapeLayer as a mask.

    e.g.:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        int radius = 100;
    
        CAShapeLayer *arc = [CAShapeLayer layer];    
        arc.path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(100, 50) radius:radius startAngle:60.0 endAngle:0.0 clockwise:YES].CGPath;
    
        arc.position = CGPointMake(CGRectGetMidX(self.view.frame)-radius,
                                   CGRectGetMidY(self.view.frame)-radius);
    
        arc.fillColor = [UIColor clearColor].CGColor;
        arc.strokeColor = [UIColor purpleColor].CGColor;
        arc.lineWidth = 15; 
        CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
        drawAnimation.duration            = 5.0; // "animate over 10 seconds or so.."
        drawAnimation.repeatCount         = 1.0;  // Animate only once..
        drawAnimation.removedOnCompletion = NO;   // Remain stroked after the animation..
        drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
        drawAnimation.toValue   = [NSNumber numberWithFloat:10.0f];
        drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
        [arc addAnimation:drawAnimation forKey:@"drawCircleAnimation"];
    
        CAGradientLayer *gradientLayer = [CAGradientLayer layer];
        gradientLayer.frame = self.view.frame;
        gradientLayer.colors = @[(__bridge id)[UIColor redColor].CGColor,(__bridge id)[UIColor blueColor].CGColor ];
        gradientLayer.startPoint = CGPointMake(0,0.5);
        gradientLayer.endPoint = CGPointMake(1,0.5);
    
        [self.view.layer addSublayer:gradientLayer];
         //Using arc as a mask instead of adding it as a sublayer.
         //[self.view.layer addSublayer:arc]; 
         gradientLayer.mask = arc;
    
    
    }
    

提交回复
热议问题