
Take some UIView
|
let myView = UIView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 200, height: 200))) |
Make and setup layer for vector shape
|
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
|
// 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
|
myLayer.path = myPath.CGPath |
Add layer to view
|
view.layer.addSublayer(myLayer) |
Now our view shows our brand new vector shape. Now we’ll animate it.
Prepare target shape for our animation
|
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
|
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
|
// 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?