How do I animate a UIView along a circular path?

心不动则不痛 提交于 2020-01-12 03:54:09

问题


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.


回答1:


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:

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.



来源:https://stackoverflow.com/questions/38416742/how-do-i-animate-a-uiview-along-a-circular-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!