如何在路径中为contentsRect属性设置动画?

时间:2011-06-13 03:16:23

标签: animation calayer bounds cakeyframeanimation

我有一个png sprite表和相应的plist文件加载,我正在尝试动画CALayer的contentsRect属性,以显示上面提到的aprite表中的sprite动画。这是一个代码:

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围绕我的精灵表移动。

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

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

1 个答案:

答案 0 :(得分:2)

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

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