Search code examples
iosuiimagecore-animationclippinguibezierpath

Animate a UIBezierPath which clips an UIImage


I have an image that looks like a donut and want to animate it so that it looks like the donut circle is not completed (stroke is not closed). It is hard to describe but imagine a speedometer which goes to 100 and you drive 50. I have done the masking with the help of a path and [path addClip] inside UIGraphicsBeginImageContextWithOptions where I also render the UIImage.

My question now is can I or how can I animate the path. I tried it with a CABasicAnimation and 2 paths (the first path where startAngle and endAngle are the same and the second path were endAngle is the desired angle) with "path" as keyPath but that is not working.

Anything helps ;)


Solution

  • I animate UIBezierPath using CABasicAnimation using...

    UIBezierPath *bezierPath = [self bezierPath];
    
    CAShapeLayer *bezierLayer = [[CAShapeLayer alloc] init];
    
    bezierLayer.path = bezierPath.CGPath;
    bezierLayer.strokeColor = [UIColor redColor].CGColor;
    bezierLayer.fillColor = [UIColor clearColor].CGColor;
    bezierLayer.lineWidth = 5.0;
    bezierLayer.strokeStart = 0.0;
    bezierLayer.strokeEnd = 1.0;
    [self.view.layer addSublayer:bezierLayer];
    
    if (animate)
    {
        CABasicAnimation *animateStrokeEnd = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
        animateStrokeEnd.duration = 1.0;
        animateStrokeEnd.fromValue = @0.0f;
        animateStrokeEnd.toValue = @1.0f;
        [bezierLayer addAnimation:animateStrokeEnd forKey:@"strokeEndAnimation"];
    }