2011-06-13 5 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; 

위의 코드는 한 I 경로 애니메이션을 비활성화로 예상 (즉 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]; 
관련 문제