iOS Animations - Part 3

Animating bezier curve

In the Last post we saw how to draw any arbitrary curves using two iOS classes viz. UIBezierPath and core animation class CAShapeLayer.

First, let us draw a UIBezierPath of our desired style and then we will animate it.

First create a UIBezierPath of desired shape. We will later use CAShapeLayer to animate it.

CGRect rect = CGRectMake(10, 10, 300, 120);
CGSize radius = CGSizeMake(50, 50);
UIRectCorner rectangleCorner = UIRectCornerBottomLeft | UIRectCornerTopRight;
UIBezierPath* customRoundedCornerBezierPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:rectangleCorner cornerRadii:radius];

Now create a progressLayer which is an instance of CAShapeLayer. We will set its path equal to the bezierPath and then add an animation to our CAShapeLayer.

CAShapeLayer* progressLayer = [[CAShapeLayer alloc] init];
[progressLayer setPath: customRoundedCornerBezierPath.CGPath];
[progressLayer setStrokeColor:[UIColor redColor].CGColor];
[progressLayer setFillColor:[UIColor clearColor].CGColor];
[progressLayer setLineWidth:3.0f];
// Begin stroking at the start of bezierPath
[progressLayer setStrokeStart:0.0];
// Terminate stroking at the end of bezierPath
[progressLayer setStrokeEnd:1.0];
[self.view.layer addSublayer:self.progressLayer];

Now create an animation for bezier path stroke operation.

// We want to animate the bezier path draw operation
CABasicAnimation* animatedStrokeEnd = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
// Set animation duration
animateStrokeEnd.duration = 5.0;
// Start from beginning of bezierPath
animateStrokeEnd.fromValue = [NSNumber numberWithFloat:0.0f];
// Terminate at the end of bezierPath
animateStrokeEnd.toValue = [NSNumber numberWithFloat:1.0f];
// Sets whether animation should be removed from layer on completion
animateStrokeEnd.removedOnCompletion = YES;

Now add an animation to the progressLayer

[progressLayer addAnimation:animateStrokeEnd forKey:nil];

Above code will animate bezierPath drawing action. It will start from one end and smoothly go to other end with the time duration mentioned for CABasicAnimation instance.

If everything went alright, you will see following animation happening on the screen.


Hope you enjoyed this post. Let me know if you have any questions about it

You can find full source code along with demo and other animation examples on GitHub Repository

Jayesh Kawli

I am a web and mobile developer working at Wayfair in Boston, MA. I come to learn so many things during course of life and I write about things which helped me and feel like they can help others too.

Subscribe to Fresh Beginning

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!