Gif图片是非常常见的图片格式,尤其是在聊天的过程中,Gif表情使用地很频繁。但是iOS竟然没有现成的支持加载和播放Gif的类。
简单地汇总了一下,大概有以下几种方法:
一、加载本地Gif文件
1、使用UIWebView
// 读取gif图片数据
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,200,200)];
[self.view addSubview:webView];
NSString *path = [[NSBundle mainBundle] pathForResource:@"001" ofType:@"gif"];
/*
NSData *data = [NSData dataWithContentsOfFile:path];
使用loadData:MIMEType:textEncodingName: 则有警告
[webView loadData:data MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
*/
NSURL *url = [NSURL URLWithString:path];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
但是使用UIWebView的弊端在于,不能设置Gif动画的播放时间。
2、将Gif拆分成多张图片,使用UIImageView播放
最好把所需要的Gif图片打包到Bundle文件内,如下图所示
- (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; //执行一次完整动画所需的时长
gifImageView.animationRepeatCount = 0; //动画重复次数
[gifImageView startAnimating];
[self.view addSubview:gifImageView];
}
3、使用SDWebImage
导入UIImage+GIF头文件
NSString *path = [[NSBundle mainBundle] pathForResource:@"gifTest" ofType:@"gif"];
NSData *data = [NSData dataWithContentsOfFile:path];
UIImage *image = [UIImage sd_animatedGIFWithData:data];
gifImageView.image = image;
君凯商联网-iOS-字唐名僧