要在 iOS 上顯示 GIF 動態圖,蘋果並沒有提供現成的元件。實務上大致分兩條路:用系統既有元件「變相」播放,或引入專門處理 GIF 的第三方庫。本文把常見方案逐一實作並比較特性。
把 GIF 資料直接餵給 UIWebView,讓 WebKit 幫你解圖並播放。
特點:載入時間稍長,但解繪品質與流暢度較佳。
// 以 WebView 顯示 GIF
- (void)showGifImageWithWebView {
// 讀取 bundle 中的 GIF 資料
NSData *gifData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"earthGif" ofType:@"gif"]];
UIWebView *imageWebView = [[UIWebView alloc] initWithFrame:CGRectMake(112, 302, 132, 102)];
imageWebView.userInteractionEnabled = NO; // 純展示,不需要互動
[imageWebView loadData:gifData MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
[self.view addSubview:imageWebView];
}
先把 GIF 拆成一張張 UIImage,再用 CAKeyframeAnimation 依每幀的顯示時間逐格切換。
特點:載入速度快,效能不如 WebView,但最大的優點是容易擴充——你能自己控制播放、暫停、指定第幾幀。
UIImage+Tool.h:
#import <UIKit/UIKit.h>
@interface UIImageView (Tool)
/** 解析 GIF 檔案資料,block 會把解析結果回傳出來 */
- (void)getGifImageWithUrk:(NSURL *)url
returnData:(void(^)(NSArray<UIImage *> *imageArray,
NSArray<NSNumber *> *timeArray,
CGFloat totalTime,
NSArray<NSNumber *> *widths,
NSArray<NSNumber *> *heights))dataBlock;
/** 為 UIImageView 加上設定 GIF 內容的便利方法 */
- (void)yh_setImage:(NSURL *)imageUrl;
@end
UIImage+Tool.m:
#import "UIImageView+Tool.h"
// 需要引入 ImageIO 才能使用 CGImageSource 系列 API
#import <ImageIO/ImageIO.h>
@implementation UIImageView (Tool)
// 解析 GIF 資料,block 中把解析結果帶出來
- (void)getGifImageWithUrk:(NSURL *)url
returnData:(void(^)(NSArray<UIImage *> *imageArray,
NSArray<NSNumber *> *timeArray,
CGFloat totalTime,
NSArray<NSNumber *> *widths,
NSArray<NSNumber *> *heights))dataBlock {
// 以檔案 URL 建立影像來源
CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)url, NULL);
// GIF 裡一共有幾張圖
size_t count = CGImageSourceGetCount(source);
float allTime = 0; // 播放一輪的總時間
NSMutableArray *imageArray = [[NSMutableArray alloc] init]; // 所有影格
NSMutableArray *timeArray = [[NSMutableArray alloc] init]; // 每幀顯示時間
NSMutableArray *widthArray = [[NSMutableArray alloc] init]; // 每幀寬度
NSMutableArray *heightArray = [[NSMutableArray alloc] init]; // 每幀高度
for (size_t i = 0; i < count; i++) {
CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
[imageArray addObject:(__bridge UIImage *)(image)];
CGImageRelease(image);
// 取出這一幀的屬性
NSDictionary *info = (__bridge NSDictionary *)CGImageSourceCopyPropertiesAtIndex(source, i, NULL);
CGFloat width = [[info objectForKey:(__bridge NSString *)kCGImagePropertyPixelWidth] floatValue];
CGFloat height = [[info objectForKey:(__bridge NSString *)kCGImagePropertyPixelHeight] floatValue];
[widthArray addObject:[NSNumber numberWithFloat:width]];
[heightArray addObject:[NSNumber numberWithFloat:height]];
// GIF 特有的資訊字典裡藏著這一幀的顯示秒數
NSDictionary *timeDic = [info objectForKey:(__bridge NSString *)kCGImagePropertyGIFDictionary];
CGFloat time = [[timeDic objectForKey:(__bridge NSString *)kCGImagePropertyGIFDelayTime] floatValue];
allTime += time;
[timeArray addObject:[NSNumber numberWithFloat:time]];
}
dataBlock(imageArray, timeArray, allTime, widthArray, heightArray);
}
- (void)yh_setImage:(NSURL *)imageUrl {
__weak id __self = self;
[self getGifImageWithUrk:imageUrl returnData:^(NSArray<UIImage *> *imageArray,
NSArray<NSNumber *> *timeArray,
CGFloat totalTime,
NSArray<NSNumber *> *widths,
NSArray<NSNumber *> *heights) {
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
NSMutableArray *times = [[NSMutableArray alloc] init];
float currentTime = 0;
// keyTimes 需要「比例」而不是絕對時間,因此逐幀正規化
for (int i = 0; i < imageArray.count; i++) {
[times addObject:[NSNumber numberWithFloat:currentTime / totalTime]];
currentTime += [timeArray[i] floatValue];
}
[animation setKeyTimes:times];
[animation setValues:imageArray];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
animation.repeatCount = MAXFLOAT; // 無限循環
animation.duration = totalTime;
[[(UIImageView *)__self layer] addAnimation:animation forKey:@"gifAnimation"];
}];
}
@end
這裡有兩個關鍵點:keyTimes 必須是 0~1 的比例值,所以要把每幀時間除以總時長做正規化;時間函式要設為 linear,否則會在每幀之間產生非預期的緩動。
- (void)showGifImageWithImageView {
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(112, 342, 132, 102)];
NSURL *url = [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:@"earthGif.gif" ofType:nil]];
[imageView yh_setImage:url];
[self.view addSubview:imageView];
}
專案位址:https://github.com/liyong03/YLGIFImage
#import "YLGIFImage.h"
#import "YLImageView.h"
- (void)showGifImageWithYLImageView {
YLImageView *imageView = [[YLImageView alloc] initWithFrame:CGRectMake(112, 342, 132, 102)];
CGFloat centerX = self.view.center.x;
[imageView setCenter:CGPointMake(centerX, 402)];
[self.view addSubview:imageView];
imageView.image = [YLGIFImage imageNamed:@"earthGif.gif"];
}
用法幾乎與原生 UIImageView 相同,替換成本極低,適合成續把既有專案改成支援 GIF。
專案位址:https://github.com/Flipboard/FLAnimatedImage
- (void)showGifImageWithFLAnimatedImage {
// 讀出 GIF 檔案
NSString *pathForFile = [[NSBundle mainBundle] pathForResource:@"earthGif" ofType:@"gif"];
NSData *dataOfGif = [NSData dataWithContentsOfFile:pathForFile];
// 建立 FLAnimatedImage
FLAnimatedImage *image = [FLAnimatedImage animatedImageWithGIFData:dataOfGif];
// 搭配專用的 ImageView 顯示
FLAnimatedImageView *imageView = [[FLAnimatedImageView alloc] init];
imageView.animatedImage = image;
imageView.frame = CGRectMake(112, 342, 132, 102);
[self.view addSubview:imageView];
}
FLAnimatedImage 的重點在於它會把影格解碼後做緩存管理,在大量 GIF 或長列表場景下,記憶體表現明顯優於把每幀都解成 UIImage 的做法。