更新:
我最近学到了另一种处理大于180度或连续旋转的方法。
有一个特殊的对象叫做CAValueFunction,它可以让您使用任意值(包括指定多个完整旋转的值)对图层的变换应用更改。
您可以创建一个CABasicAnimation来控制图层的变换属性,但是不需要提供变换,而是提供一个NSNumber,表示新的旋转角度。如果您提供一个像20pi这样的新角度,您的图层将会旋转10个完整的旋转(2pi/rotation)。代码如下:
//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”的方法中。