如何沿圆形路径为UIView设置动画? [英] How do I animate a UIView along a circular path?
问题描述
在Swift代码中,如何启动 UIView
并为其设置动画,以使其沿圆形路径运动,然后优雅地结束?是否可以使用 CGAffineTransform
动画实现此目的?
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?
我在下面准备了一个GIF,显示了我要实现的动画类型。
I have prepared a GIF below showing the type of animation I'm trying to achieve.
推荐答案
已更新:将代码更新为Swift4。使用 #keyPath
而不是 keyPath
的字符串文字。
Updated: Update code to Swift 4. Use #keyPath
rather than string literal for keyPath
.
使用 UIBezierPath
和 CAKeyFrameAnimation
。
这是代码:
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)
这是捕获内容:
此外,您可以设置 anchorPoint $
squareView.layer
的c $ c>属性,以使视图不动画固定在其中心。 anchorPoint
的默认值为(0.5,0.5),表示中心点。
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.
这篇关于如何沿圆形路径为UIView设置动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!