CABasicAnimation旋转返回到原来的位置

我旋转CALayer使用CABasicAnimation,并正常工作。 问题是,当我尝试旋转同一图层时,它将在旋转之前返回到其原始位置。 我预期的结果是,下一轮,它应该从结束的地方开始。 这是我的代码:

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"]; animation.fromValue = 0; animation.toValue = [NSNumber numberWithFloat:3.0]; animation.duration = 3.0; animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; animation.removedOnCompletion = NO; animation.fillMode = kCAFillModeForwards; animation.autoreverses = NO; [calayer addAnimation:animation forKey:@"rotate"]; 

我的代码有什么缺失? 谢谢

发生什么事是你在表示层看到animation。 但是,这并不会更新图层的实际位置。 所以,一旦animation结束,你会看到图层,因为它没有改变。

真的很值得阅读“核心animation渲染架构” 。 否则,这可能是非常混乱。

要解决这个问题,请按如下方式将CABasicAnimation设置为CABasicAnimation

[animation setDelegate:self];

然后,创build一个方法来设置animation完成时所需的目标属性。 现在,这是令人困惑的部分。 您应该在animationDidStart而不是animationDidStop上执行此操作。 否则,表示层animation将完成,当看到calayer处于原始位置时,您将看到闪烁,然后跳转到目标位置(无animation)。 试试animationDidStop ,你会明白我的意思。

我希望这不是太混乱!

 - (void)animationDidStart:(CAAnimation *)theAnimation { [calayer setWhateverPropertiesExpected]; } 

编辑:

后来我发现苹果推荐了一个更好的方法来做到这一点。

Oleg Begemann在他的博客文章中有一个很好的描述, 当使用显式CAAnimations时,Prevent图层不会陷入原始值

基本上你所做的是在你开始animation之前,你要记下图层的当前值,即原始值:

 // Save the original value CGFloat originalY = layer.position.y; 

接下来,在图层模型上设置toValue 。 因此,无论您要做什么animation ,图层模型都具有最终的价值

 // Change the model value layer.position = CGPointMake(layer.position.x, 300.0); 

然后,您将animation从“值”设置为上面提到的原始值:

 CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position.y"]; // Now specify the fromValue for the animation because // the current model value is already the correct toValue animation.fromValue = @(originalY); animation.duration = 1.0; // Use the name of the animated property as key // to override the implicit animation [layer addAnimation:animation forKey:@"position"]; 

请注意,上面的编辑中的代码是从Ole Begemann的博客复制/粘贴的

如果您希望animation从结束位置开始,请将fromValue属性设置为CALayer的当前旋转。

获得这个值是棘手的,但是这个SOpost告诉你如何: https : //stackoverflow.com/a/6706604/1072846