如何在 Swift 中控制动画旋转方向超过 180°?

Dav*_*mes 6 animation ios swift

根据文档rotated(by:)

\n\n
\n

角度

\n\n

仿射变换旋转的角度(以弧度为单位)。在 iOS 中,正值指定逆时针旋转,负值指定顺时针旋转。

\n
\n\n

这引起了很多混乱,并已部分得到解答,但即使我们接受坐标系被翻转(并且只是执行与文档所述相反的操作),它在动画时仍然提供不一致的结果。

\n\n

旋转方向(顺时针或逆时针)取决于目标旋转与当前旋转的接近程度:

\n\n
    \n
  • <= 180\xc2\xba顺时针动画
  • \n
  • > 180\xc2\xba逆时针动画
  • \n
\n\n

使用UIView.animateUIViewPropertyAnimator显示不一致:

\n\n
// Animates CLOCKWISE\nUIView.animate(withDuration: 2.0) {\n    let radians = Angle(179).radians // 3.12413936106985\n    view.transform = view.transform.rotated(by: CGFloat(radians))\n}\n// Animates COUNTER-CLOCKWISE\nUIViewPropertyAnimator(duration: 2, curve: .linear) {\n    let radians = Angle(181).radians // 3.15904594610974\n    view.transform = view.transform.rotated(by: CGFloat(radians))\n}\n// Does not animate\nUIViewPropertyAnimator(duration: 2, curve: .linear) {\n    let radians = Angle(360).radians // 6.28318530717959\n    view.transform = view.transform.rotated(by: CGFloat(radians))\n}\n
Run Code Online (Sandbox Code Playgroud)\n

Dav*_*mes 2

答案是用于CABasicAnimation超过 180\xc2\xba 的旋转,请记住正值是顺时针方向负值是逆时针方向

\n\n
// Rotate 360\xc2\xba clockwise.\nlet rotate = CABasicAnimation(keyPath: "transform.rotation")\nrotate.fromValue = Angle(0).radians\nrotate.toValue = Angle(360).radians\nrotate.duration = 2.0\nself.layer.add(rotate, forKey: "transform.rotation")\n
Run Code Online (Sandbox Code Playgroud)\n