3

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

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"];

我的代码有什么遗漏吗?谢谢

4

2 回答 2

16

发生的事情是您在表示层中看到了动画。但是,这不会更新图层的实际位置。因此,一旦动画完成,您会看到图层原样,因为它没有更改。

《核心动画渲染架构》真的很值得一读。否则,这可能会非常混乱。

要修复它,请为您设置一个委托,CABasicAnimation如下所示:

[animation setDelegate:self];

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

我希望这不会太混乱!

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

编辑:

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

Oleg Begemann在他的博客文章中对正确的技术进行了很好的描述,防止层在使用显式 CAAnimations 时恢复到原始值

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

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

接下来,在层的模型上设置toValue 。因此,图层模型具有您将要执行的任何动画的最终值

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

然后,您将动画设置为fromValue为您上面提到的原始值:

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 的博客中复制/粘贴的

于 2011-10-07T17:37:10.107 回答
1

如果您希望动画从结束的地方开始,则将fromValue属性设置为CALayer的当前旋转。

获得该值很棘手,但这篇 SO 帖子向您展示了如何:https ://stackoverflow.com/a/6706604/1072846

于 2012-09-20T14:35:00.793 回答