Matt Spoon
Matt Spoon

Reputation: 2840

How to animate drawing a UIBezierPath in swift

Does anybody know how to animate the drawing of an UIBezierPath within a custom view? So it looks like the iPhone has picked up a pen and is drawing on the screen slow enough to see it.

just say I have a path like the following:

var bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPointMake(49.5, 14.5))
bezierPath.addCurveToPoint(CGPointMake(106.5, 14.5), controlPoint1: CGPointMake(106.5, 14.5), controlPoint2: CGPointMake(106.5, 14.5))
bezierPath.addCurveToPoint(CGPointMake(119.5, 26.5), controlPoint1: CGPointMake(106.5, 14.5), controlPoint2: CGPointMake(119.5, 14.5))
bezierPath.addCurveToPoint(CGPointMake(119.5, 75.5), controlPoint1: CGPointMake(119.5, 38.5), controlPoint2: CGPointMake(119.5, 75.5))
bezierPath.addCurveToPoint(CGPointMake(106.5, 88.5), controlPoint1: CGPointMake(119.5, 75.5), controlPoint2: CGPointMake(122.5, 88.5))
bezierPath.addCurveToPoint(CGPointMake(49.5, 88.5), controlPoint1: CGPointMake(90.5, 88.5), controlPoint2: CGPointMake(49.5, 88.5))
bezierPath.addCurveToPoint(CGPointMake(36.5, 75.5), controlPoint1: CGPointMake(49.5, 88.5), controlPoint2: CGPointMake(36.5, 89.5))
bezierPath.addCurveToPoint(CGPointMake(36.5, 26.5), controlPoint1: CGPointMake(36.5, 61.5), controlPoint2: CGPointMake(36.5, 26.5))
bezierPath.addCurveToPoint(CGPointMake(49.5, 14.5), controlPoint1: CGPointMake(36.5, 26.5), controlPoint2: CGPointMake(35.5, 14.5))
UIColor.redColor().setFill()
bezierPath.fill()
UIColor.blackColor().setStroke()
bezierPath.lineWidth = 10
bezierPath.stroke()

This draws a rounded rectangle and is written inside the drawRect function of a custom class.

Does anybody know how to animate the drawing of this?

Upvotes: 5

Views: 5288

Answers (1)

jtbandes
jtbandes

Reputation: 118751

You might consider using a CAShapeLayer and animating the strokeEnd property (you can use CABasicAnimation to control the details of the animation). This post has an example.

Upvotes: 8

Related Questions