更新:
我最近了解到另一种处理大于 180 度的旋转或连续旋转的方法。
有一个称为 CAValueFunction 的特殊对象,可让您使用任意值(包括指定多个完整旋转的值)对图层的变换进行更改。
您创建图层变换属性的 CABasicAnimation,但随后提供的值不是提供变换,而是提供新旋转角度的 NSNumber。如果您提供像 20pi 这样的新角度,您的图层将旋转 10 个完整旋转(2pi/旋转)。代码如下所示:
//Create a CABasicAnimation object to manage our rotation.
CABasicAnimation *rotation = [CABasicAnimation animationWithKeyPath:@"transform"];
rotation.duration = 10.0;
CGFLOAT angle = 20*M_PI;
//Set the ending value of the rotation to the new angle.
rotation.toValue = @(angle);
//Have the rotation use linear timing.
rotation.timingFunction =
[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
/*
This is the magic bit. We add a CAValueFunction that tells the CAAnimation we are
modifying the transform's rotation around the Z axis.
Without this, we would supply a transform as the fromValue and toValue, and
for rotations > a half-turn, we could not control the rotation direction.
By using a value function, we can specify arbitrary rotation amounts and
directions and even rotations greater than 360 degrees.
*/
rotation.valueFunction =
[CAValueFunction functionWithName: kCAValueFunctionRotateZ];
/*
Set the layer's transform to it's final state before submitting the animation, so
it is in it's final state once the animation completes.
*/
imageViewToAnimate.layer.transform =
CATransform3DRotate(imageViewToAnimate.layer.transform, angle, 0, 0, 1.0);
[imageViewToAnimate.layer addAnimation:rotation forKey:@"transform.rotation.z"];
(我从一个工作示例应用程序中提取了上面的代码,并取出了一些与主题没有直接关系的东西。您可以在 github 上的项目KeyframeViewAnimations (链接)中看到正在使用的此代码。执行旋转的代码在一个名为“handleRotate”的方法中