Search code examples
iosobjective-cxcodecashapelayercaanimation

Create coloured circle based on value(360) or percentage(100%)


This code creating a complete circle but I want to create a circle based on value either 360 or percentage 100%. IF percentage is 56% I want 56% circle. Like this based on percentage/value, I want circle.

CAShapeLayer *circle = [CAShapeLayer layer];
circle.path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(29, 29) radius:27 startAngle:-M_PI_2 endAngle:2 * M_PI - M_PI_2 clockwise:YES].CGPath;
circle.fillColor = [UIColor clearColor].CGColor;
circle.strokeColor = [UIColor greenColor].CGColor;
circle.lineWidth = 4;

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
animation.duration = 10;
animation.removedOnCompletion = NO;
animation.fromValue = @(0);
animation.toValue = @(1);
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
[circle addAnimation:animation forKey:@"drawCircleAnimation"];

[_colouredCircle.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)];
[_colouredCircle.layer addSublayer:circle];

Solution

  • That means that your toValue should match your percentage.

    In your case, animation.toValue = @(0.56); would end the stroke at 56% of the circle (0...1 range).

    See this answer for information about keeping the final animated value after completion.

    TLDR: You have to also update the model layer.

    circle.strokeStart = 0;
    circle.strokeEnd   = 0.56; // Your target value
    ...
    // Your animation