把多張圖片整合成連續動畫,是很多 iOS 開發者會用到的功能。透過 UIImageView 的 animationImages 屬性,就能輕鬆實現。以下分別示範單次(有限次)播放與循環播放的程式碼。
animationImageView.animationImages = imageFrames; // imageFrames 是一個圖片陣列
[UIView setAnimationDelegate:self];
animationImageView.animationDuration = 0.75f;
animationImageView.animationRepeatCount = 3;
[animationImageView startAnimating];
shouldPlay = NO;
NSInteger timeout = 3;
[NSTimer scheduledTimerWithTimeInterval:timeout target:self selector:@selector(stopAnimation) userInfo:nil repeats:NO];這段程式碼設定動畫的播放時長與重複次數,並透過 NSTimer 在指定時間後呼叫 stopAnimation 停止動畫。
若將 animationRepeatCount 設為 0,動畫便會無限循環播放:
UIImageView *animView = [[UIImageView alloc] initWithFrame:self.view.frame];
animView.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"01.gif"],
[UIImage imageNamed:@"02.gif"],
[UIImage imageNamed:@"03.gif"], nil];
animView.animationDuration = 1.75; // all frames will execute in 1.75 seconds
animView.animationRepeatCount = 0; // repeat the animation forever
[animView startAnimating]; // start animating
[self.view addSubview:animView]; // add the animation view to the main window透過 animationImages 提供圖片陣列、設定 animationDuration 控制播放速度、再用 animationRepeatCount 決定播放次數,就能靈活實現單次或循環的連續動畫效果。