もっと良い方法があるようです。画像が多すぎない場合は、animationImages
のプロパティを使用することをお勧め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
}];
これらすべてをメモリに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;
}
}