要做一個tableview,cell內全部展示的是GIF。GIF是由多個image組成的,測試過後,得到幾種使用方法,介紹一下:
1.最省心的,使用sdwebimage,使用imageview sdsetimageWithUrl: placeHolder:這個方法就可以,sd內部做好了緩存處理,上啦下拉tableview的時候cell刷新,也不會卡頓,效果最好。
2.使用webview。有兩種,一個是wkwebview,一個是UIwebview,使用UIwebview的時候如果有加載進度條的需求不太好做,如果沒有這個需求則正常使用就行。如果有這個需求那麼建議使用wkwebview。創建wkwebview之後,創建一個progressview,給wkwebview添加一個觀察者,鍵名是estimatedProgress
[_wkwebview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
觀察方法中,CGFloat newProgress = [[change valueForKey:NSKeyValueChangeNewKey] doubleValue];這個就是進度。
完整觀察方法:
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
if ([keyPath isEqualToString:@"estimatedProgress"]) {
CGFloat newProgress = [[change valueForKey:NSKeyValueChangeNewKey] doubleValue];
if ([change[@"new"] floatValue] < [change[@"old"] floatValue]) {
return;
}
if (newProgress == 1) {
_progress.hidden = YES;
[_progress setProgress:0];
}else{
_progress.hidden = NO;
[_progress setProgress:newProgress animated:YES];
}
}
}
這樣可以在你添加的位置和時間需要展示progress就行了
3.使用三方FLAnimatedImageView
這個就是用來顯示GIF的,FLAnimatedImageView是一個繼承與UIimageView的子類,有一個FLAnimatedImage 類型的屬性,主要用到了這個來顯示gif,我是這麼用的,使用sdwebimagemanager 初始化一個圖片下載管理器,使用它調用loadimage方法下載圖片。在下載回調用有圖片數據的image,和圖片的所有data,在回調內切到主線程,對FLAnimatedImageView對象的FLAnimatedImage屬性賦值即可。在回調內注意將圖片保存到本地,下次滑動cell的時候先查看本地是否有該圖片,沒有就下載,有就直接拿來展示,代碼:
NSData *data = [LGUtils getCacheImageWithKey:record.img];//record.img是你傳進來的gif的地址,我在這裏下載完成後當成鍵名把圖片的data給存起來了
if (data.length > 0) {
_animateImageView.animateImage = [UIImage animatedImageWithGIFData:data];
}else{
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager loadImageWithURL:[NSURL URLWithString:record.img] options:SDWebImageRetryFailed progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
if (data.length > 0) {
[LGUtils saveImageDataTocache:data withKey:record.img];
dispatch_async(dispatch_get_main_queue(), ^{
_animateImageView.animateImage = [UIImage animatedImageWithGIFData:data];
})
}
}];
}
代碼裏的如何存儲圖片到本地cache文件夾,和取出文件 去網上找吧,一大堆
三種方法都試過,第三種尚可,有點慢,第一種最快,省心,cell滑動時候不影響效果,第二種不好,webview展示GIF效果還是差點。webview還要針對image的大小做適配,使用imageview展示則可以通過設置設置圖片的顯示方式contentmode完善顯示效果