Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I animate a UIView along a circular path?

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

like image 635
user4806509 Avatar asked Jul 17 '16 00:07

user4806509


1 Answers

Updated: Update code to Swift 5.6

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.path = circlePath.cgPath
animation.duration = 1
animation.repeatCount = .infinity

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 show 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 screenshot:

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.

like image 104
Cokile Ceoi Avatar answered Oct 20 '22 23:10

Cokile Ceoi