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

在Swift代码中,我如何启动和动画UIView ,使其沿着圆形路径移动,然后优雅地结束? 是否可以使用CGAffineTransform动画实现此目的?

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

在此处输入图像描述

更新:更新代码到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) 

这是捕获:

在此处输入图像描述

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