iOS 加载gif
一、WebView加载
可以通过WebView加载本地Gif图和网络Gif图,但图片大小不能自适应控件大小,也不能设置Gif图播放时间。使用如下:
UIWebView *webView = self.viewArr[0];
// 本地地址
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"hello" ofType:@"gif"];
NSURL *imageUrl = [NSURL URLWithString:imagePath];
NSURLRequest *request = [NSURLRequest requestWithURL:imageUrl];
[webView loadRequest:request];
二、UIImageView加载多图动画
把动态图拆分成一张张图片,将一系列帧添加到animationImages数组里面,然后设置animation一系列属性,如动画时间,动画重复次数。例:
UIImageView *imageView;
NSMutableArray *imageArr = [NSMutableArray arrayWithCapacity:3];
for (int i = 0; i<3; i++) {
NSString *imageStr = [NSString stringWithFormat:@“gif%d”,i + 1];
UIImage *image = [UIImage imageNamed:imageStr];
[imageArr addObject:image];
}
imageView.animationImages = imageArr;
imageView.animationDuration = 2;
[imageView startAnimating];
三、SDWebImage加载本地GIF
在SDWebImage这个库里有一个UIImage+GIF的类别,使用sd_animatedGIFWithData方法可以将GIF图片数据专为图片。例:
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@“gif” ofType:@“gif”];
NSData *imageData = [NSData dataWithContentsOfFile:imagePath];
UIImage *image = [UIImage sd_animatedGIFWithData:imageData];
UIImageView *imageView;
imageView.image = image;
四、SDWebImage加载网络GIF
首先将网络gif图下载到本地,然后再用sd_animatedGIFWithData方法,转为可用的图片,下载gif图的方式有两种
方式一:采用SDWebImageDownloader下载,回调里面会有NSData。只是,你会发现采用SDWebImageDownloader下载,界面显示就是没有sd_setImageWithURL方法流畅,这是因为sd_setImageWithURL里面对cache和线程做了很多处理,保证了UI的流畅。
NSString *imageStr = @“http://baidu.gif”;
NSURL *imgeUrl = [NSURL URLWithString:imageStr];
SDWebImageDownloaderOptions options = 0;
UIImageView *imageView = self.viewArr[3];
// 方法一 SDWebImageDownloader下载
SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader];
[downloader downloadImageWithURL:imgeUrl
options:options
progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
} completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
imageView.image = [UIImage sd_animatedGIFWithData:data];
}];
方式二、sd_setImageWithURL下载,回调的时候不用image,去直接读cache。(首先要了解sd_setImageWithURL里的内部逻辑,下载完之后先入cache,再执行block,这才保证外面可以直接读取到),取出来的就是NSData。首次下载成功时,可能获取data失败,因为这次图片可能还没存储成功,有延迟。
SDWebImageOptions opt = SDWebImageRetryFailed | SDWebImageAvoidAutoSetImage;
[imageView sd_setImageWithURL:imgeUrl
placeholderImage:nil
options:opt
completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
if (image.images && image.images.count) {
NSString *path = [[SDImageCache sharedImageCache] defaultCachePathForKey:imageURL.absoluteString];
NSData *data = [NSData dataWithContentsOfFile:path];
UIImage *gifImage = [UIImage sd_animatedGIFWithData:data];
imageView.image = gifImage;
}
}];