Vector Layer Animation Basics Cheat Sheet

Take some UIView
1 2 3 |
let myView = UIView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 200, height: 200))) |
Make and setup layer for vector shape
1 2 3 4 5 6 7 8 9 |
let myLayer = CAShapeLayer() // setup combining of paths if they overlap myLayer.fillRule = kCAFillRuleEvenOdd // set colors of shapes myLayer.fillColor = UIColor.blackColor().CGColor myLayer.strokeColor = UIColor.redColor().CGColor // set thick of stroke layer.lineWidth = 2.0 |
Make path for shape layer
1 2 3 4 5 6 7 8 9 10 |
// we'll need CGPath, // but UIBezierPath has friendlier methods for drawing shapes let myPath = UIBezierPath() // draw shape myPath.moveToPoint(CGPoint(x: 0, y: 0)) myPath.addLineToPoint(CGPoint(x: myView.bounds.width * 0.7, y: 0)) myPath.addLineToPoint(CGPoint(x: myView.bounds.width * 0.7, y: myView.bounds.height * 0.7)) myPath.addLineToPoint(CGPoint(x: 0, y: myView.bounds.height * 0.7)) myPath.closePath() |
Add path to layer
1 2 |
myLayer.path = myPath.CGPath |
Add layer to view
1 2 |
view.layer.addSublayer(myLayer) |
Now our view shows our brand new vector shape. Now we’ll animate it.
Prepare target shape for our animation
1 2 3 4 5 6 7 |
let targetPath = UIBezierPath() targetPath.moveToPoint(CGPoint(x: myView.bounds.width * 0.3, y: myView.bounds.height * 0.3)) targetPath.addLineToPoint(CGPoint(x: myView.bounds.width, y: myView.bounds.height * 0.3)) targetPath.addLineToPoint(CGPoint(x: myView.bounds.width, y: myView.bounds.height)) targetPath.addLineToPoint(CGPoint(x: myView.bounds.width * 0.3, y: myView.bounds.height)) targetPath.closePath() |
Setup animation
1 2 3 4 5 6 7 8 9 10 11 |
let animation = CABasicAnimation(keyPath: "path") // shape on the beginning of animation // we can use current shape on the layer by // (view.layer.presentationLayer() as? CAShapeLayer)?.path animation.fromValue = path.CGPath // shape on the end of animation animation.toValue = targetPath.CGPath animation.duration = 2.0 animation.removedOnCompletion = false animation.fillMode = kCAFillModeBoth |
Add animation to layer
1 2 3 4 5 |
// if there can be another animations, you can remove them myLayer.removeAllAnimations() // add animation to layer myLayer.addAnimation(animation, forKey: animation.keyPath) |
That’s all. Easy, isn’t it?