UIStepper(點擊條)、AVAudioPlayer(音頻)、UIImageView 動畫(動態圖)、UIBlurEffect(毛玻璃)與 UISlider(滑塊)。它們共同構成了一個小型多媒體展示頁,下面挑幾個重點來看。
iOS 原生的 UIImageView 不支援 GIF 檔本身,但可以用「把動畫拆成一堆連續圖片」的方式模擬。做法是把所有幀載入陣列,指定給 animationImages,再設定播放間隔與次數。
self.picArr = [NSMutableArray array];
for (NSInteger i = 0; i < 24; i++) {
NSString *picName = [NSString stringWithFormat:@"pie_%0.2ld.jpg", i];
UIImage *image = [UIImage imageNamed:picName];
[self.picArr addObject:image];
}
self.tomCatImageView.animationImages = self.picArr;
self.tomCatImageView.animationDuration = 5;
self.tomCatImageView.animationRepeatCount = 1000;
[self.tomCatImageView startAnimating];
檔案命名規則很重要,%0.2ld 會補零成 00、01、02…,這正好對應連續幀的命名慣例。
iOS 8 之後提供 UIVisualEffectView,只要指定一個 UIBlurEffect 樣式就能獲得系統級的模糊渲染,效能遠優於自己截圖做高斯模糊。
UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]; UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect]; effectView.alpha = 0.7; effectView.frame = imageView.frame; [imageView addSubview:effectView];
把 UISlider 的 value 直接綁到動畫的 animationDuration 上,就能做出「拖動滑桿調整播放速度」的效果。這裡的最小值 0.5、最大值 5 對應的是整段動畫播放完所需的秒數。
self.slider.minimumValue = 0.5;
self.slider.maximumValue = 5;
[self.slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
- (void)sliderAction:(UISlider *)slider {
NSLog(@"%g", slider.value);
self.tomCatImageView.animationDuration = self.slider.value;
[self.tomCatImageView startAnimating];
}
AVAudioPlayer 播放本地音檔的標準流程是:先從 mainBundle 取到檔案路徑,轉成 NSURL 後初始化播放器,再呼叫 play。若要控制音量,可以搭配 UIStepper 的 value 即時調整 player.volume。
NSString *path = [[NSBundle mainBundle] pathForResource:@"李白" ofType:@"mp3"]; self.play = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil]; [self.play play];
UISegmentedControl 則是分段切換的經典控件,用 initWithItems: 傳入陣列建立,透過 selectedSegmentIndex 讀取當前選項,tintColor 控制配色。這幾個控件學會之後,大多數中小型 App 的界面元素都能拼裝出來了。