2

我有一个 png 精灵表和相应的 plist 文件已加载,我正在尝试为 CALayer 的 contentsRect 属性设置动画,以显示来自上述 aprite 表的精灵动画。这是一个代码:

CGFloat width = myLayer.frame.size.width;
CGFloat height = myLayer.frame.size.height;
myLayer.bounds = CGRectMake( 0, 0, width, height );
myLayer.contentsGravity = kCAGravityCenter;
myLayer.contents=(id)pImage; // This is my sprite sheet


CAKeyframeAnimation *keyFrameContentsRectAnimation = [CAKeyframeAnimation animationWithKeyPath:@"contentsRect"];
keyFrameContentsRectAnimation.path = pAnimationPath; // This is a path to animate on
keyFrameContentsRectAnimation.values = pRects; // This is an array of normalized CGRects representing sprite sheet
keyFrameContentsRectAnimation.fillMode = kCAFillModeRemoved;
keyFrameContentsRectAnimation.calculationMode = kCAAnimationDiscrete;
keyFrameContentsRectAnimation.duration=pAnimationDuration;
keyFrameContentsRectAnimation.repeatCount = 1;

只要我禁用路径动画(即从 keyFrameContentsRectAnimation 注释掉路径属性),上面的代码似乎就可以按预期工作 - 动画有效并且 contentsRect 围绕我的精灵表移动。

但问题是:我的所有精灵都需要在图层框架内进行一些偏移,以使我的动画看起来正确(偏移量因透明度裁剪而异)。

所以我想如果我从我拥有的这些偏移点创建一个路径并将其放入我应该解决问题的动画的路径属性中。不幸的是,事实并非如此......只要我添加路径属性,而不是精灵动画,我会在动画期间看到整个精灵表图像......我错过了什么?

4

1 回答 1

2

好吧,经过一些阅读和实验,我有了一个可行的解决方案......为了让精灵出现在正确的位置,我必须将另一个动画添加到动画组中并将 CALayer 剪辑到我的精灵的尺寸:

myLayer.bounds = CGRectMake( 0, 0, 256.0, 256.0 ); //my sprite dimentions

myLayer.contentsGravity = kCAGravityCenter;
myLayer.contents=(id)pImage; // This is my sprite sheet


CAKeyframeAnimation *keyFrameContentsRectAnimation = [CAKeyframeAnimation animationWithKeyPath:@"contentsRect"];

keyFrameContentsRectAnimation.values = pRects; // This is an array of normalized CGRects representing sprite sheet
keyFrameContentsRectAnimation.fillMode = kCAFillModeRemoved;
keyFrameContentsRectAnimation.calculationMode = kCAAnimationDiscrete;
keyFrameContentsRectAnimation.duration=pAnimationDuration;
keyFrameContentsRectAnimation.repeatCount = 1;  

CAKeyframeAnimation* kfanim = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
kfanim.path = pAnimationPath;
kfanim.values = pRects;
kfanim.fillMode = kCAFillModeBoth;
kfanim.calculationMode = kCAAnimationDiscrete;
kfanim.duration=pAnimationDuration;
kfanim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];


NSArray *animations = [NSArray arrayWithObjects:keyFrameContentsRectAnimation,
                       kfanim, nil];

CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
[animationGroup setDuration:pAnimationDuration];
[animationGroup setRepeatCount: 1];
[animationGroup setAnimations:animations];
于 2011-06-13T12:52:05.417 回答