似乎有可能會有更好的方法。如果你沒有太多的圖像,我可能只是建議使用的UIImageView
animationImages
屬性,然後startAnimating
:
NSArray *images = @[[UIImage imageNamed:@"0.jpg"],
[UIImage imageNamed:@"1.jpg"],
[UIImage imageNamed:@"2.jpg"],
[UIImage imageNamed:@"3.jpg"],
[UIImage imageNamed:@"4.jpg"],
[UIImage imageNamed:@"5.jpg"],
[UIImage imageNamed:@"6.jpg"],
[UIImage imageNamed:@"7.jpg"]];
self.imageView.image = images[0];
self.imageView.animationImages = images;
self.imageView.animationDuration = kAnimationDuration;
self.imageView.animationRepeatCount = 1;
[self.imageView startAnimating];
[UIView animateWithDuration:kAnimationDuration
animations:^{
self.imageView.center = ... // set this to whatever you want
}];
如果您擔心加載所有這一切到內存中,你也可以使用一個CADisplayLink
來加載圖像作爲適當的,像下面這樣:
- (void)animateImageUsingDisplayLink
{
self.imageNames = @[@"0.jpg",
@"1.jpg",
@"2.jpg",
@"3.jpg",
@"4.jpg",
@"5.jpg",
@"6.jpg",
@"7.jpg"];
self.imageView.image = [UIImage imageNamed:self.imageNames[0]];
[self startDisplayLink];
[UIView animateWithDuration:kAnimationDuration
animations:^{
self.imageView.center = ... // set this to whatever you want
}];
}
- (void)startDisplayLink
{
self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)];
self.startTime = CACurrentMediaTime();
[self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
- (void)stopDisplayLink
{
[self.displayLink invalidate];
self.displayLink = nil;
}
- (void)handleDisplayLink:(CADisplayLink *)displayLink
{
CFTimeInterval elapsed = displayLink.timestamp - self.startTime;
// If you want it to repeat, then comment out the following `if` statement
if (elapsed >= kAnimationDuration)
{
[self stopDisplayLink];
return;
}
NSInteger frameNumber = ((NSInteger) elapsed * [self.imageNames count]/kAnimationDuration) % [self.imageNames count];
if (frameNumber != self.currentFrameNumber)
{
self.imageView.image = [UIImage imageNamed:self.imageNames[frameNumber]];
self.currentFrameNumber = frameNumber;
}
}
來源
2013-03-26 04:35:30
Rob
如果什麼第5幀中,說如果球員被移動到左邊,我希望它中斷5幀,它會移動到右邊從那個框架?我可以調用stopDisplayLink在它完成之前中斷它,然後開始一個新的顯示鏈接序列嗎? – mskw 2013-03-26 05:03:37
@mskw是的,這應該工作。試試看。僅供參考,如果你想重複動畫,你可能需要像上面那樣調整frameNumber,然後註釋掉if(elapsed> = kAnimationDuration)...塊。但希望你明白這個主意。 – Rob 2013-03-26 08:09:22
@mskw我可能誤解了你的問題。如果您希望動畫從停止的位置繼續播放,您需要調整「CADisplayLink」代碼(例如,在設置一次後不要重置「startTime」)。 – Rob 2013-03-26 16:02:35