iOS Swift - 如何使用 CABasicAnimation 和 CATransform3DRotate 以及 "m34" 变换来制作 360 度翻转动画?

iOS Swift - How to do 360 degree flip animation using CABasicAnimation and CATransform3DRotate with "m34" transform?

尽管我尽了最大努力,但我无法弄清楚如何使用 CATransform3DRotate 从左到右制作 UIView 的完整循环旋转动画。请注意,我已经可以使用 CABasicAnimation 将其旋转 360 度,但不使用 CATransform3DRotate。但是,我想对透视深度使用 .m34 变换。涉及 UIView.animate/transitions 的解决方案对我要实现的目标没有帮助。非常感谢任何帮助。

编辑: 我在 Whosebug 和其他地方广泛搜索,但没有找到任何描述如何使用 CATransform3DRotate 进行 360 度旋转的内容。打电话给顶级枪手寻求帮助,因为这是一个以前似乎没有得到回答的问题。谢谢!

这是将 UIView 旋转 180 度的代码。

var transform = CATransform3DIdentity
transform.m34 = 1.0 / -200.0

let animation = CABasicAnimation(keyPath: "transform")
animation.toValue = CATransform3DRotate(transform, CGFloat( Double.pi), 0, 1, 0)
animation.duration = 0.8
animation.beginTime = 0.0
animation.fillMode = .forwards
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
cardView.layer.add(animation, forKey: "360flip")

您当前的代码正在替换动画层的整个变换,这意味着您不能对其应用透视变换。您还遇到了结束状态在数学上与开始状态相同的问题,为了解决这个问题,您尝试将动画链接在一起,并使用填充模式,这使得整个事情变得更加复杂。

首先,我们来处理转换。要获得您想要设置图层变换的 .m34 的透视图,您已经在这样做:

var perspective = CATransform3DIdentity
perspective.m34 = 1 / -200
cardView.layer.transform = perspective

接下来,为了仅触及图层变换的旋转,您可以使用比transform更精确的关键路径:

let rotate = CABasicAnimation(keyPath: "transform.rotation.y")
rotate.fromValue = 0

这将使图层的其余变换保持不变。

最后,当动画结束与开始相同时,如何强制动画引擎注意到差异?使用 byValue:

rotate.byValue = CGFloat.pi * 2

这会强制图层绕到 360 度,而不是呆在原地的懒惰捷径。

最终的完整代码是:

var perspective = CATransform3DIdentity
perspective.m34 = 1 / -200
cardView.layer.transform = perspective
let rotate = CABasicAnimation(keyPath: "transform.rotation.y")
rotate.fromValue = 0
rotate.byValue = CGFloat.pi * 2
rotate.duration = 2
cardView.layer.add(rotate, forKey: nil)

给出这个结果: