Skip to content

Instantly share code, notes, and snippets.

@AliSoftware
Created August 3, 2017 13:07
Show Gist options
  • Save AliSoftware/a7be50178f1106e51de382b1bf975c5b to your computer and use it in GitHub Desktop.
Save AliSoftware/a7be50178f1106e51de382b1bf975c5b to your computer and use it in GitHub Desktop.
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 = UIColor.orange.withAlphaComponent(0.3).cgColor
shape.strokeColor = UIColor.orange.cgColor
shape.lineWidth = 3
view.layer.addSublayer(shape)
//: 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: view.center, ray: 200, curvature: CGPoint(x: 250, y: -20))
let star2 = star(center: view.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