似乎有更好的方法。如果您没有太多图像,我可能会建议使用thenanimationImages
的属性:UIImageView
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
}];
如果您担心将所有这些加载到内存中,您还可以使用 aCADisplayLink
来适当地加载图像,如下所示:
- (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;
}
}