4

我正在这样设置动画:

self.testAnimation = [CAKeyframeAnimation animationWithKeyPath:@"TestAnimation"];

[self.animationImagesAsCGImages addObject:( id )[UIImage imageNamed:@"c1.png"].CGImage];
[self.animationImagesAsCGImages addObject:( id )[UIImage imageNamed:@"c2.png"].CGImage];
[self.animationImagesAsCGImages addObject:( id )[UIImage imageNamed:@"c3.png"].CGImage];
[self.animationImagesAsCGImages addObject:( id )[UIImage imageNamed:@"c4.png"].CGImage];

[self.animationKeyframeTimings addObject:[NSNumber numberWithFloat:0.0f]];
[self.animationKeyframeTimings addObject:[NSNumber numberWithFloat:0.25f]];
[self.animationKeyframeTimings addObject:[NSNumber numberWithFloat:0.5f]];
[self.animationKeyframeTimings addObject:[NSNumber numberWithFloat:0.75f]];

self.testAnimation.values          = self.animationImagesAsCGImages;
self.testAnimation.keyTimes        = self.animationKeyframeTimings;

self.testAnimation.repeatCount     = HUGE_VALF;
self.testAnimation.autoreverses    = NO;
self.testAnimation.calculationMode = kCAAnimationDiscrete;
self.testAnimation.duration        = 2.0f;

然后这样称呼它:

[self.layer addAnimation:self.testAnimation forKey:@"TestAnimation"];

但什么都没有显示。

我看过其他几篇关于 kCAAnimationDiscrete 的 Stack 帖子需要第一个时间为 0.0f,如您所见。

请指教?

4

1 回答 1

13

tl;dr:将动画关键路径更改为contents,如下所示:

self.testAnimation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];

为什么它不起作用

当您编写时,[CAKeyframeAnimation animationWithKeyPath:@"TestAnimation"];您正在尝试为TestAnimation不存在的图层上的属性设置动画。因此,对该属性的任何更改都没有视觉效果。

animationWithKeyPath:对比addAnimation:forKey:

keyPath忽略创建动画和将动画添加key到图层之间的区别并不少见。

创建新动画时,您可以将 keyPath 指定给应该动画的属性。如果您在没有 keyPath 的情况下创建动画,则可以使用动画上的 keyPath 属性对其进行设置。

向图层添加动画时,您可以指定一个关键点。此键仅用于使用 CALayer 上的 animationForKey: 方法访问动画。

如何使它工作

由于您正在将图像添加到您的值中,因此我假设您想要在图像之间进行动画处理,在这种情况下,您应该使用该contents属性作为关键路径。

从内容属性的文档中:

提供图层内容的对象。动画。

...

您可以将此属性设置为 aCGImageRef以显示图像的内容来代替图层的内容。

于 2012-08-08T18:51:16.260 回答