2011-06-13 77 views
2

我有一個PNG精靈表和相應的plist文件加載,我試圖動畫CALayer的contentsRect屬性顯示從上述aprite表精靈動畫。下面是一個代碼:如何沿着路徑動畫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在我的精靈表移動。

但問題在於:爲了讓我的動畫看起來正確(偏移取決於透明度裁剪),我的所有精靈都需要在一個圖層框架內進行一些偏移。

所以我想,如果我從這些偏移點創建一個路徑,並將其獲取到我的動畫的路徑屬性中,以解決問題。不幸的是,情況並非如此...... 只要我添加路徑屬性,而不是動畫動畫,我就會在動畫期間看到整個動畫表格圖像...我錯過了什麼?

回答

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