UIImage 用來定義一張圖片,而 UIImageView 則是承載圖片的視圖容器,把圖片放進去顯示。除了靜態顯示,UIImageView 還能輕鬆實現逐幀動畫。下面透過程式碼說明。
- (void)viewDidLoad {
[super viewDidLoad];
// 建立 imageView,可同時指定正常圖片與高亮圖片
// UIImageView *imageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1"] highlightedImage:[UIImage imageNamed:@"2"]];
UIImageView *imageV = [[UIImageView alloc] init];
imageV.frame = CGRectMake(100, 100, 150, 300);
// 是否允許用戶與控件交互
imageV.userInteractionEnabled = YES;
// 設定圖片渲染顏色
imageV.tintColor = [UIColor greenColor];
// 準備動畫用的圖片數組
NSMutableArray *arrayM = [NSMutableArray array];
for (int i = 0; i < 40; i++) {
NSString *name = [NSString stringWithFormat:@"eat_%02d", i];
UIImage *image = [UIImage imageNamed:name];
[arrayM addObject:image];
}
// 設定動畫圖片數組
imageV.animationImages = arrayM;
// 設定播放次數(0 表示無限循環)
imageV.animationRepeatCount = 1;
// 設定總播放時間
imageV.animationDuration = arrayM.count * 0.08;
// 開始播放動畫
[imageV startAnimating];
[self.view addSubview:imageV];
}
- (void)startAnimating {
NSLog(@"%s", __func__);
}
- (void)stopAnimating {
NSLog(@"%s", __func__);
}
- (BOOL)isAnimating {
NSLog(@"%s", __func__);
return YES;
}
透過 animationImages 提供一組圖片、設定 animationDuration 與 animationRepeatCount,再呼叫 startAnimating,就能實現類似 GIF 的逐幀動畫效果;而 stopAnimating 則用於停止播放,isAnimating 可用來查詢當前是否正在播放。