GIF 動畫的本質是一串連續的靜態畫面,而每一幀的停留時間未必相同。如果播放時忽略各幀自帶的 delay time,所有幀就會以固定節奏推進,成品與原圖的節奏落差往往相當明顯。
為了解決這個問題,可以自行封裝一個解析 GIF 的工具類:先從檔案讀出總幀數與每一幀的顯示時間,再把這些時間換算成權重,交給 CAKeyframeAnimation 驅動播放。
以下是我寫好的解析與播放工具類:
// // SvGifView.h // SvGifSample // // Created by maple on 3/28/13. // Copyright (c) 2013 smileEvday. All rights reserved. // #import <UIKit/UIKit.h> @interface SvGifView : UIView /* * @brief desingated initializer */ - (id)initWithCenter:(CGPoint)center fileURL:(NSURL*)fileURL; /* * @brief start Gif Animation */ - (void)startGif; /* * @brief stop Gif Animation */ - (void)stopGif; /* * @brief get frames image(CGImageRef) in Gif */ + (NSArray*)framesInGif:(NSURL*)fileURL; @end
//
// SvGifView.m
// SvGifSample
//
// Created by maple on 3/28/13.
// Copyright (c) 2013 smileEvday. All rights reserved.
//
#import "SvGifView.h"
#import <ImageIO/ImageIO.h>
#import <QuartzCore/CoreAnimation.h>
/*
* @brief resolving gif information
*/
void getFrameInfo(CFURLRef url, NSMutableArray *frames, NSMutableArray *delayTimes,
CGFloat *totalTime, CGFloat *gifWidth, CGFloat *gifHeight)
{
CGImageSourceRef gifSource = CGImageSourceCreateWithURL(url, NULL);
// get frame count
size_t frameCount = CGImageSourceGetCount(gifSource);
for (size_t i = 0; i < frameCount; ++i) {
// get each frame
CGImageRef frame = CGImageSourceCreateImageAtIndex(gifSource, i, NULL);
[frames addObject:(id)frame];
CGImageRelease(frame);
// get gif info with each frame
NSDictionary *dict = (NSDictionary*)CGImageSourceCopyPropertiesAtIndex(gifSource, i, NULL);
NSLog(@"kCGImagePropertyGIFDictionary %@",
[dict valueForKey:(NSString*)kCGImagePropertyGIFDictionary]);
// get gif size
if (gifWidth != NULL && gifHeight != NULL) {
*gifWidth = [[dict valueForKey:(NSString*)kCGImagePropertyPixelWidth] floatValue];
*gifHeight = [[dict valueForKey:(NSString*)kCGImagePropertyPixelHeight] floatValue];
}
// kCGImagePropertyGIFDictionary 中
// 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; // seconds
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"];
NSMutableArray *times = [NSMutableArray arrayWithCapacity:3];
CGFloat currentTime = 0;
int count = _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];
}
// remove contents when animation end
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
self.layer.contents = nil;
}
@end程式碼不長,邏輯也單純。最開頭那個 C 函式負責解析 GIF,之所以寫成 C 函式而不是 Objective-C 方法,是因為它需要一次回傳多個資訊(幀陣列、時間陣列、總時長、寬高),而 Objective-C 方法只能回傳單一物件;況且兩者混編本身毫無障礙。
// 設定位置和大小 CGRect frame = CGRectMake(50, 50, 0, 0); frame.size = [UIImage imageNamed:@"guzhang.gif"].size; // 讀取 gif 圖片數據 NSData *gif = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"guzhang" ofType:@"gif"]]; // view 生成 UIWebView *webView = [[UIWebView alloc] initWithFrame:frame]; webView.userInteractionEnabled = NO; // 用戶不可交互 [webView loadData:gif MIMEType:@"image/gif" textEncodingName:nil baseURL:nil]; [self.view addSubview:webView]; [webView release];
UIImageView *gifImageView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
NSArray *gifArray = [NSArray arrayWithObjects:
[UIImage imageNamed:@"1"],
[UIImage imageNamed:@"2"],
[UIImage imageNamed:@"3"],
// …… 依序帶入其餘各幀 ……
[UIImage imageNamed:@"22"], nil];
gifImageView.animationImages = gifArray; // 動畫圖片數組
gifImageView.animationDuration = 5; // 播放一輪所需的總時長
gifImageView.animationRepeatCount = 1; // 動畫重複次數
[gifImageView startAnimating];
[self.view addSubview:gifImageView];
[gifImageView release];要留意的是,這種做法無法保留各幀不同的間隔——animationDuration 是平均分攤到每一幀上的,因此一旦原圖的幀間時間不一致,播放節奏就會失真。若在意還原度,仍建議走前面的解析方案。