如何为路径上的contentsRect属性设置动画?

| 我有一个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中注释掉path属性),上面的代码似乎就可以正常工作-动画起作用并且contentRect在我的Sprite工作表中移动。 但这是问题所在:我的所有子画面都需要在图层框架内有一定的偏移量才能使我的动画看起来正确(偏移量取决于透明度裁剪)。 因此,我想出了是否可以从这些偏移点创建路径并将其放入动画的path属性中,该属性应该可以解决该问题。不幸的是,事实并非如此…… 一旦添加路径属性,而不是精灵动画,我就会在动画期间看到整个精灵表图像...我错过了什么?     
已邀请:
        好吧,经过一番阅读和实验之后,我有了一个可行的解决方案...为了使精灵显示在正确的位置,我必须在动画组中添加另一个动画并将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];
    

要回复问题请先登录注册