如何沿圆形路径为UIView设置动画?

use*_*509 6 animation uiview cgaffinetransform ios swift

在Swift代码中,我如何启动并设置动画UIView,使其沿圆形路径移动,然后优雅地结束?是否可以使用CGAffineTransform动画实现这一目标?

我在下面准备了一个GIF,展示了我想要实现的动画类型.

在此输入图像描述

Cok*_*eoi 25

更新:更新代码到Swift 4.使用#keyPath而不是字符串文字keyPath.

使用UIBezierPathCAKeyFrameAnimation.

这是代码:

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)
Run Code Online (Sandbox Code Playgroud)

这是捕获:

在此输入图像描述

此外,您可以设置anchorPoint属性squareView.layer以使视图不是动画锚定在其中心.默认值为anchorPoint(0.5,0.5),表示中心点.