Skip to content

Instantly share code, notes, and snippets.

@prat14k
Forked from AliSoftware/morphing.swift
Last active July 27, 2018 11:08
Show Gist options
  • Save prat14k/49afa8ced6ea3f9bc54e236f7a23730d to your computer and use it in GitHub Desktop.
Save prat14k/49afa8ced6ea3f9bc54e236f7a23730d to your computer and use it in GitHub Desktop.
A simple demo of doing some morphing using CAShapeLayer & UIBezierPath. Animation done using CABasicAnimation.
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
func addLabel() {
let label = UILabel()
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
label.text = "Hello World!"
label.textColor = .black
view.addSubview(label)
}
override func loadView() {
let view = UIView()
view.backgroundColor = .white
self.view = view
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
starShow()
}
func starShow() {
//: 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
//: 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)
view.layer.addSublayer(shape)
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment