如何在圆形路径上使UIView动画?

12

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

我准备了下面的 GIF 显示我想要实现的动画类型。

进入图像描述

1个回答

36

更新:将代码更新为Swift 5.6

使用UIBezierPathCAKeyFrameAnimation

以下是代码:

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)

这是截图:

在此输入图片描述

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


@CokileCeoi 是否需要执行任何操作才能开始动画?我已经实现了与上面完全相同的代码,只是替换了自己的图像和路径,但没有动画发生... 我可以看到路径和UIImage,但UIImage对我来说仍然静止不动... - Justin
哦,没事了!我知道这完全是微不足道的,哈哈。我没有意识到在 let animation = CAKeyframeAnimation(keyPath: "position") 中,(keyPath: "position") 实际上引用了一个必需的属性... 我以为你可以将键路径字符串命名为任何你想要的东西哈哈:P现在可以用了! - Justin
我在viewDidLoad()中添加了CAKeyframeAnimation,但我希望在点击按钮后开始动画。 - krishan kumar
@krishankumar 您可以将调用add(_:forKey:)方法移动到您的按钮单击回调中。 - Cokile Ceoi
可能是与 https://dev59.com/KJ_ha4cB1Zd3GeqPsAet 相似的重复问题。 - matt
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接