dynamic island animation in swift

One approach to create a dynamic island animation in Swift is to use UIViewPropertyAnimator and UIBezierPath. Here are the steps:

  1. Create a CAShapeLayer for the island shape, set its fill color and add it to a view's layer.
main.swift
let islandLayer = CAShapeLayer()
islandLayer.fillColor = UIColor.brown.cgColor
view.layer.addSublayer(islandLayer)
115 chars
4 lines
  1. Generate a UIBezierPath for the island shape. You can use UIBezierPath's move(to:), addLine(to:) and addCurve(to:controlPoint1:controlPoint2:) functions to construct the path.
main.swift
let islandPath = UIBezierPath()
islandPath.move(to: CGPoint(x: 100, y: 200))
islandPath.addLine(to: CGPoint(x: 300, y: 200))
islandPath.addCurve(to: CGPoint(x: 200, y: 100), controlPoint1: CGPoint(x: 350, y: 100), controlPoint2: CGPoint(x: 275, y: 50))
islandPath.close()
272 chars
6 lines
  1. Create a UIViewPropertyAnimator with a duration and set the animation block for the fractionComplete property.
main.swift
let animator = UIViewPropertyAnimator(duration: 5, curve: .linear) {
    islandLayer.path = islandPath.cgPath
}
112 chars
4 lines
  1. Start the animation by calling animator.startAnimation().

You can also add a CAKeyframeAnimation for some extra animation effects. For example, to make the island rotate and tilt while moving, use:

main.swift
let rotation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
rotation.duration = 5
rotation.values = [0, 0.2, -0.2, 0.2, 0]
rotation.keyTimes = [0, 0.25, 0.5, 0.75, 1]
islandLayer.add(rotation, forKey: "rotation")

let tilt = CAKeyframeAnimation(keyPath: "transform.rotation.x")
tilt.duration = 5
tilt.values = [0, 0.2, -0.2, 0.2, 0]
tilt.keyTimes = [0, 0.25, 0.5, 0.75, 1]
islandLayer.add(tilt, forKey: "tilt")
419 chars
12 lines

This will make the island rotate around its center and tilt up and down while moving.

gistlibby LogSnag