Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A simple demo of doing some morphing using CAShapeLayer & UIBezierPath
import UIKit
import PlaygroundSupport
// Create a view to display the result in playground
let view = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
view.backgroundColor = .white
PlaygroundPage.current.liveView = view;
//: Add a CAShapeLayer to it, configure its line & fill colors
let shape = CAShapeLayer()
shape.frame = view.bounds.insetBy(dx: 10, dy: 10)
shape.fillColor =
shape.strokeColor =
shape.lineWidth = 3
//: Function to create a BezierPath drawing a 4-branches star
func star(center: CGPoint, ray: CGFloat, curvature: CGPoint) -> UIBezierPath {
// Build a ✧ star
var path = UIBezierPath()
path.move(to: CGPoint(x: center.x+ray, y: center.y))
path.addQuadCurve(to: CGPoint(x: center.x, y: center.y+ray), controlPoint: CGPoint(x: center.x-curvature.y, y: center.y-curvature.x))
path.addQuadCurve(to: CGPoint(x: center.x-ray, y: center.y), controlPoint: CGPoint(x: center.x+curvature.x, y: center.y-curvature.y))
path.addQuadCurve(to: CGPoint(x: center.x, y: center.y-ray), controlPoint: CGPoint(x: center.x+curvature.y, y: center.y+curvature.x))
path.addQuadCurve(to: CGPoint(x: center.x+ray, y: center.y), controlPoint: CGPoint(x: center.x-curvature.x, y: center.y+curvature.y))
return path
let star1 = star(center:, ray: 200, curvature: CGPoint(x: 250, y: -20))
let star2 = star(center:, ray: 200, curvature: CGPoint(x: -20, y: 250))
//: Start with star1
shape.path = star1.cgPath
//: Create the animation from star1 to star2 (infinitely repeat, autoreverse)
let animation = CABasicAnimation(keyPath: "path")
animation.toValue = star2.cgPath
animation.duration = 1
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
animation.fillMode = kCAFillModeBoth
animation.repeatCount = .greatestFiniteMagnitude // Infinite repeat
animation.autoreverses = true
animation.isRemovedOnCompletion = false
shape.add(animation, forKey: animation.keyPath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.