2

pngスプライトシートと対応するplistファイルをロードし、CALayerのcontentsRectプロパティをアニメーション化して、上記のスプライトシートからスプライトアニメーションを表示しようとしています。コードは次のとおりです。

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 に答える