這個小專案示範了幾個實用的基礎技巧:用 Plist 檔管理大量素材清單、用 UIImageView 播放序列框動畫、以及用 AudioServices 播放音效。適合當作 iOS 動畫與多媒體的入門練習。
#import@interface ViewController : UIViewController // 湯姆貓的圖像視圖 @property (weak, nonatomic) IBOutlet UIImageView *tomcatImageView; // 動畫操作入口 - (IBAction)animationAction:(UIButton *)sender; @end
#import "ViewController.h"
// 用列舉取代魔法數字,讓程式碼可讀性更好
typedef enum
{
kTomCatFart = 0, // 放屁
kTomCatCymbal, // 打鈸
kTomcatDrink, // 喝牛奶
kTomCatEat, // 吃鳥
kTomCatPie, // 拍餅
kTomCatScratch, // 刮玻璃
kTomCatKnockout, // 打臉
kTomCatStomach, // 拍肚皮
kTomCatFootRight, // 右腳
kTomCatFootLeft, // 左腳
kTomCatAngryTail // 甩尾巴
} kTomCatAnimationType;
@interface ViewController ()
{
NSMutableDictionary *_tomcatDict; // 湯姆貓的動畫資料
NSMutableDictionary *_soundDict; // 音效 ID 快取
}
@end
@implementation ViewController
/**
* 以檔案名稱載入並建立 SystemSoundID
* 用字典快取,避免同一個音效被重複載入
*/
- (SystemSoundID)loadSoundId:(NSString *)soundFile
{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:soundFile ofType:nil]];
SystemSoundID soundId;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundId);
return soundId;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// 1. 指定 Plist 路徑
NSString *path = [[NSBundle mainBundle] pathForResource:@"Tomcat" ofType:@"plist"];
// 2. 一次載入所有動畫的設定
_tomcatDict = [NSMutableDictionary dictionaryWithContentsOfFile:path];
NSLog(@"%@", _tomcatDict);
// 3. 初始化音效快取字典
_soundDict = [NSMutableDictionary dictionary];
}
#pragma mark - Actions
- (IBAction)animationAction:(UIButton *)sender
{
// 動畫進行中不允許被打斷
if ([_tomcatImageView isAnimating])
{
return;
}
// 依按鈕 tag 取出對應的動畫設定
NSDictionary *dict;
switch (sender.tag)
{
case kTomCatAngryTail:
dict = _tomcatDict[@"angry-tail"];
break;
case kTomCatFart:
dict = _tomcatDict[@"fart"];
break;
case kTomCatCymbal:
dict = _tomcatDict[@"cymbal"];
break;
case kTomcatDrink:
dict = _tomcatDict[@"drink"];
break;
case kTomCatEat:
dict = _tomcatDict[@"eat"];
break;
case kTomCatPie:
dict = _tomcatDict[@"pie"];
break;
case kTomCatScratch:
dict = _tomcatDict[@"scratch"];
break;
default:
break;
}
// 依設定組出序列框圖片陣列
NSMutableArray *imageList = [NSMutableArray array];
for (NSInteger i = 0; i < [dict[@"frames"] integerValue]; i++)
{
NSString *imageFile = [NSString stringWithFormat:dict[@"imageFormat"], i];
UIImage *image = [UIImage imageNamed:imageFile];
[imageList addObject:image];
}
// ---- 音效處理 ----
// 1. 取出這個動畫對應的音效檔名清單
NSArray *array = dict[@"soundFiles"];
SystemSoundID soundId = 0;
if (array.count > 0)
{
// 2. 逐一確認音效是否已載入過,沒有的就建立並快取
for (NSString *fileName in array)
{
SystemSoundID playSoundId = [_soundDict[fileName] unsignedLongValue];
if (playSoundId <= 0)
{
playSoundId = [self loadSoundId:fileName];
// 字典只能存物件,NSInteger 需用 @() 包裝成 NSNumber
[_soundDict setValue:@(playSoundId) forKey:fileName];
}
}
NSLog(@"============================");
NSLog(@"%@", _soundDict);
// 3. 隨機挑一個音效播放,增加新鮮感
NSInteger seed = arc4random_uniform(array.count);
NSString *fileName = array[seed];
soundId = [_soundDict[fileName] unsignedLongValue];
}
// ---- 啟動動畫 ----
[_tomcatImageView setAnimationImages:imageList];
[_tomcatImageView setAnimationDuration:[dict[@"frames"] integerValue] / 10.0];
[_tomcatImageView setAnimationRepeatCount:1];
[_tomcatImageView startAnimating];
// ---- 播放音效 ----
if (soundId > 0)
{
AudioServicesPlaySystemSound(soundId);
}
}
@end
用 Plist 驅動素材。把「每個動畫有幾張圖、檔名格式、對應音效」全部寫進 Plist,程式碼完全不需要為新增動畫而修改。這在素材數量多、設計師隨時會調整的專案裡特別有用。
用列舉取代 tag 數字。switch 裡寫 kTomCatFart 遠比寫 0 清楚,也避免 Storyboard 上 tag 變動後無從察覺。
音效 ID 要快取。AudioServicesCreateSystemSoundID 每次都會配置系統資源,重複建立同一個音效是浪費。用字典快取後,同一個音效只會建立一次。
用 AudioServicesCreateSystemSoundID 建立的資源,必須在不再使用時呼叫 AudioServicesDisposeSystemSoundID(soundId) 釋放,否則會造成資源洩漏。建議在 dealloc 中遍歷 _soundDict 逐一釋放。