我使用以下代码旋转图像:
CABasicAnimation *rotationAnimation;
rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 /* full rotation*/ * 1];
rotationAnimation.duration = 1; // this results in a speed of one full rotation per second
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount = 100;
rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
[self.imageView.layer addAnimation:rotationAnimation forKeyPath:@"rotationAnimation"];
当动画正常结束时,在100次旋转之后,动画的结尾与动画的开头相匹配,所以我不必担心与层匹配的presentationLayer(这可能会导致快照效果)。 / p>
但是,如果我结束此操作,请使用:
[self.imageView.layer removeAnimationForKey:@"rotationAnimation"];
当用户点击停止按钮时,我可以将presentationLayer与图层匹配,否则我会回弹到原始状态。
我试过了:
id value = [((CALayer *)self.imageView.layer.presentationLayer) valueForKeyPath:@"transform.rotation.z"];
[self.imageView.layer setValue:value forKey:@"transform.rotation.z"];
无效(似乎没有做任何事情),并且:
self.imageView.layer.transform = ((CALayer *)self.imageView.layer.presentationLayer).transform;
也不起作用(我在45°XY轴周围发生奇怪的扭曲)。
我不确定还有什么可以尝试的。在过去,当我不得不做类似的事情时,我只需要匹配presentationLayer的位置,或大小或......,但我从来没有必须匹配它的旋转位置。
谢谢。
答案 0 :(得分:0)
虽然这不是我要找的答案,但这是我目前的解决方法。我仍然希望有人有更好的方式(并将分享: - )。
如果我不能将当前图层设置为与presentationLayer相同的位置,那么我将在让它运行单个旋转的剩余部分之后停止动画,因此它最终会在与图层看起来像:
- (void) runSpinAnimation:(BOOL) run;
{
id value = [((CALayer *)self.imageView.layer.presentationLayer) valueForKeyPath:@"transform.rotation.z"];
CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
[self.imageView.layer removeAnimationForKey:@"rotationAnimation"];
if (run) {
rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 /* full rotation*/ * 1];
rotationAnimation.duration = 1;
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount = MAXFLOAT;
rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
[self.imageView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}
else {
float radians = ((NSNumber *)value).floatValue;
if (radians < 0)
radians = M_PI + radians;
rotationAnimation.fromValue = @(radians);
rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 1.0 /* full rotation*/ * 1];
rotationAnimation.duration = 0.25;
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount = 1;
rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
[self.imageView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}
}