轉(zhuǎn)載:iOS之加載Gif圖片
作者:鏡花水月_I
1、使用UIWebView
// 讀取gif圖片數(shù)據(jù)
NSData *data = [NSData dataWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"001" ofType:@"gif"]];
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
[webView loadData:data MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
[self.view addSubview:webView];
但是使用UIWebView的弊端在于,不能設(shè)置Gif動畫的播放時間。
2、UIImageView播放(幀動畫)
最好把所需要的Gif圖片打包到Bundle文件內(nèi),如圖:

- (NSArray *)animationImages
{
NSFileManager *fielM = [NSFileManager defaultManager];
NSString *path = [[NSBundle mainBundle] pathForResource:@"Loading" ofType:@"bundle"];
NSArray *arrays = [fielM contentsOfDirectoryAtPath:path error:nil];
NSMutableArray *imagesArr = [NSMutableArray array];
for (NSString *name in arrays) {
UIImage *image = [UIImage imageNamed:[(@"Loading.bundle") stringByAppendingPathComponent:name]];
if (image) {
[imagesArr addObject:image];
}
}
return imagesArr;
}
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *gifImageView = [[UIImageView alloc] initWithFrame:frame];
gifImageView.animationImages = [self animationImages]; //獲取Gif圖片列表
gifImageView.animationDuration = 5; //執(zhí)行一次完整動畫所需的時長
gifImageView.animationRepeatCount = 1; //動畫重復(fù)次數(shù)
[gifImageView startAnimating];
[self.view addSubview:gifImageView];
}
3、使用SDWebImage(UIImage+GIF的類別)
在SDWebImage這個庫里有一個UIImage+GIF的類別,里面為UIImage擴(kuò)展了三個方法:
@interface UIImage (GIF)
+ (IImage *)sd_animatedGIFNamed:(NSString *)name;
+ (UIImage *)sd_animatedGIFWithData:(NSData *)data;
- (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size;
@end
注意:第一個只需要傳Gif的名字,而不需要帶擴(kuò)展名(如Gif圖片名字為001@2x.gif,只需傳001即可)
我們就使用第二個方法試一試效果:
NSString *path = [[NSBundle mainBundle] pathForResource:@"gifTest" ofType:@"gif"];
NSData *data = [NSData dataWithContentsOfFile:path];
UIImage *image = [UIImage sd_animatedGIFWithData:data];
gifImageView.image = image;
我們來看下此方法的內(nèi)部實(shí)現(xiàn):
+ (UIImage *)sd_animatedGIFWithData:(NSData *)data {
if (!data) {
return nil;
}
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
size_t count = CGImageSourceGetCount(source);
UIImage *animatedImage;
if (count <= 1) {
animatedImage = [[UIImage alloc] initWithData:data];
}
else {
NSMutableArray *images = [NSMutableArray array];
NSTimeInterval duration = 0.0f;
for (size_t i = 0; i < count; i++) {
CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
duration += [self sd_frameDurationAtIndex:i source:source];
[images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];
CGImageRelease(image);
}
if (!duration) {
duration = (1.0f / 10.0f) * count;
}
animatedImage = [UIImage animatedImageWithImages:images duration:duration];
}
CFRelease(source);
return animatedImage;
}
總結(jié)
1、使用UIWebView不可以設(shè)置duration,其他兩種方法都可設(shè)置。而且方法1的容器為UIWebView ,其余兩種的容器都是大家熟悉的UIImageView
2、方法2和方法3需要對應(yīng)看應(yīng)用場景。