Smooth Path Animations in Swift
Animating a path is an easy way to add a natural, smooth effect to your app. Just look at Bentoblox:
The code for something like this is simple. We can accomplish something basic in 4 easy steps:
- Specify an origin point and a destination point:
let origin = view.center
let destination = CGPoint(x: origin.x, y: origin.y + 100)
2. Create a CAShapeLayer with a few basic parameters and a UIBezierpath for it to follow:
let shapeLayer = CAShapeLayer()
let path = UIBezierPath(rect: CGRect(origin: origin, size: .zero))shapeLayer.lineWidth = 30.0
shapeLayer.strokeColor = UIColor.purple.cgColor
shapeLayer.lineCap = kCALineCapRoundpath.addLine(to: destination)
shapeLayer.path = path.cgPath
3. Create an animation for the strokeEnd property of the CAShapeLayer
let animation = CABasicAnimation(keyPath: “strokeEnd”)
animation.fromValue = 0.0
animation.toValue = 1.0
animation.duration = 2.0
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
4. Add the layer to the containing view’s layer hierarchy, and add the animation to the layer.
view.layer.addSublayer(shapeLayer)
shapeLayer.add(animation, forKey: nil)
It’s that simple.
You’ll discover more neat things like this in BentoBlox — check out the game here on the App Store.