How do I animate a UIView along a circular path?

user4806509 picture user4806509 · Jul 17, 2016 · Viewed 7.8k times · Source

In Swift code, how can I start and animate a UIView so that it moves in a motion along a circular path, then bring it to an end gracefully? Is it possible to achieve this using a CGAffineTransform animation?

I have prepared a GIF below showing the type of animation I'm trying to achieve.

enter image description here

Answer

Cokile Ceoi picture Cokile Ceoi · Jul 17, 2016

Updated: Update code to Swift 4. Use #keyPath rather than string literal for keyPath.

Use UIBezierPath and CAKeyFrameAnimation.

Here is the code:

let circlePath = UIBezierPath(arcCenter: view.center, radius: 20, startAngle: 0, endAngle: .pi*2, clockwise: true)

let animation = CAKeyframeAnimation(keyPath: #keyPath(CALayer.position))
animation.duration = 1
animation.repeatCount = MAXFLOAT
animation.path = circlePath.cgPath

let squareView = UIView()
// whatever the value of origin for squareView will not affect the animation
squareView.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
squareView.backgroundColor = .lightGray
view.addSubview(squareView)
// You can also pass any unique string value for key
squareView.layer.add(animation, forKey: nil)

// circleLayer is only used to locate the circle animation path
let circleLayer = CAShapeLayer()
circleLayer.path = circlePath.cgPath
circleLayer.strokeColor = UIColor.black.cgColor
circleLayer.fillColor = UIColor.clear.cgColor
view.layer.addSublayer(circleLayer)

Here is the capture:

enter image description here

Moreover, you can set the anchorPoint property of squareView.layer to make the view not animate anchored in it's center. The default value of anchorPoint is (0.5, 0.5) which means the center point.