聊天時我們常丟一張搞笑的 GIF 表情,一張圖勝過千言萬語。原本以為 GIF 這麼常見的格式,各平台多少都會支援,直到某次專案需要用 GIF 當過場動畫,翻了半天官方文件才發現:iOS 並沒有現成用來載入與播放 GIF 的類別。
網路上可以參考的做法大致有兩類(例如「三種方式顯示 GIF 圖片」與 andrei512 的 GIFLoader),共同點都是借助 ImageIO 函式庫解析 GIF 檔案,再自行驅動動畫播放。
但仔看會發現一個共同缺陷:它們都沒有處理每一幀各自的顯示時長。GIF 格式本身允許每幀設定不同的延遲時間,若一律用固定間隔播放,節奏就會失真——該停久一點的畫面一閃而過,該快速掃過的段落反而拖沓。
於是自己寫一個解析工具類,目標是:正確讀出每一幀的延遲時間,並依各自的節奏播放。
整體流程三步:
1. 用 ImageIO 的 CGImageSourceCreateWithURL 載入 GIF 檔。
2. 透過 CGImageSource 取得總幀數,並逐幀讀出顯示時間。
3. 用 CAKeyframeAnimation 依時間軸播放這些幀。
#import <UIKit/UIKit.h> @interface SvGifView : UIView // 指定初始化的設計 - (id)initWithCenter:(CGPoint)center fileURL:(NSURL *)fileURL; // 開始播放 GIF 動畫 - (void)startGif; // 停止播放 - (void)stopGif; // 取出 GIF 中的所有幀(CGImageRef) + (NSArray *)framesInGif:(NSURL *)fileURL; @end
#import "SvGifView.h"
#import <ImageIO/ImageIO.h>
#import <QuartzCore/CoreAnimation.h>
// 解析 GIF 的各項資訊
void getFrameInfo(CFURLRef url,
NSMutableArray *frames,
NSMutableArray *delayTimes,
CGFloat *totalTime,
CGFloat *gifWidth,
CGFloat *gifHeight)
{
CGImageSourceRef gifSource = CGImageSourceCreateWithURL(url, NULL);
size_t frameCount = CGImageSourceGetCount(gifSource);
for (size_t i = 0; i < frameCount; ++i) {
// 取出第 i 幀
CGImageRef frame = CGImageSourceCreateImageAtIndex(gifSource, i, NULL);
[frames addObject:(id)frame];
CGImageRelease(frame);
// 取出該幀的屬性字典
NSDictionary *dict = (NSDictionary *)CGImageSourceCopyPropertiesAtIndex(gifSource, i, NULL);
// 取得整體尺寸
if (gifWidth != NULL && gifHeight != NULL) {
*gifWidth = [[dict valueForKey:(NSString *)kCGImagePropertyPixelWidth] floatValue];
*gifHeight = [[dict valueForKey:(NSString *)kCGImagePropertyPixelHeight] floatValue];
}
// kCGImagePropertyGIFDelayTime 與 kCGImagePropertyGIFUnclampedDelayTime 數值相同
NSDictionary *gifDict = [dict valueForKey:(NSString *)kCGImagePropertyGIFDictionary];
[delayTimes addObject:[gifDict valueForKey:(NSString *)kCGImagePropertyGIFDelayTime]];
if (totalTime) {
*totalTime = *totalTime +
[[gifDict valueForKey:(NSString *)kCGImagePropertyGIFDelayTime] floatValue];
}
}
}
@interface SvGifView ()
{
NSMutableArray *_frames;
NSMutableArray *_frameDelayTimes;
CGFloat _totalTime; // 秒
CGFloat _width;
CGFloat _height;
}
@end
@implementation SvGifView
- (id)initWithCenter:(CGPoint)center fileURL:(NSURL *)fileURL
{
self = [super initWithFrame:CGRectZero];
if (self) {
_frames = [[NSMutableArray alloc] init];
_frameDelayTimes = [[NSMutableArray alloc] init];
_width = 0;
_height = 0;
if (fileURL) {
getFrameInfo((CFURLRef)fileURL, _frames, _frameDelayTimes,
&_totalTime, &_width, &_height);
}
self.frame = CGRectMake(0, 0, _width, _height);
self.center = center;
}
return self;
}
+ (NSArray *)framesInGif:(NSURL *)fileURL
{
NSMutableArray *frames = [NSMutableArray arrayWithCapacity:3];
NSMutableArray *delays = [NSMutableArray arrayWithCapacity:3];
getFrameInfo((CFURLRef)fileURL, frames, delays, NULL, NULL, NULL);
return frames;
}
- (void)startGif
{
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
// 把每幀的延遲時間換算成佔整體時長的比例,作為 keyTimes
NSMutableArray *times = [NSMutableArray arrayWithCapacity:3];
CGFloat currentTime = 0;
int count = (int)_frameDelayTimes.count;
for (int i = 0; i < count; ++i) {
[times addObject:[NSNumber numberWithFloat:(currentTime / _totalTime)]];
currentTime += [[_frameDelayTimes objectAtIndex:i] floatValue];
}
[animation setKeyTimes:times];
NSMutableArray *images = [NSMutableArray arrayWithCapacity:3];
for (int i = 0; i < count; ++i) {
[images addObject:[_frames objectAtIndex:i]];
}
[animation setValues:images];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
animation.duration = _totalTime;
animation.delegate = self;
animation.repeatCount = 5;
[self.layer addAnimation:animation forKey:@"gifAnimation"];
}
- (void)stopGif
{
[self.layer removeAllAnimations];
}
// 動畫結束後清掉 contents,避免殘影
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
self.layer.contents = nil;
}
@end
為什麼用 C 函式做解析。因為需要一次回傳多項資訊(幀陣列、延遲陣列、總時長、寬高),而 Objective-C 的方法只能回傳一個值。C 語言可用指標參數輸出多個結果,加上 Objective-C 與 C 本來就能無縫混用,這個選擇最省事。
keyTimes 的算法。CAKeyframeAnimation 的 keyTimes 必須是 0 到 1 之間的遞增數值,代表每個關鍵畫面在整體時長中的相對位置。把每幀的累積延遲除以總時長,就得到正確的時間軸分佈——這正是多數現成範例省略、卻最影響觀看體驗的一步。
repeatCount 與 contents 清理。動畫結束後把 layer 的 contents 設為 nil,是為了避免最後一幀永久留在畫面上。若要無限循環,把 repeatCount 設為 HUGE_VALF 並移除這段清理即可。
這個方案在當時是必要的自力救濟。隨著 iOS 版本演進,情況已大不相同:UIImage 從 iOS 13 起可直接載入 GIF 並自動播放,WKWebView 與 SDWebImage、Kingfisher 等函式庫也都能處理動圖。新專案沒必要再手刻解析邏輯;但理解 ImageIO 與 CAKeyframeAnimation 的組合方式,在需要自訂播放節奏、逐幀取圖或做特殊轉場時仍然派得上用場。
原始範例專案:https://github.com/smileEvday/SvGifView/