iOS 加载本地Gif图片
生活随笔
收集整理的這篇文章主要介紹了
iOS 加载本地Gif图片
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
記錄一個(gè)iOS 加載本地gif格式圖片的方法
項(xiàng)目中需要加載本地gif圖片,一開始使用的是SDWebImage框架的
- (nullable UIImage *)sd_imageWithGIFData:(nullable NSData *)data;
但是在部分機(jī)型上出現(xiàn)了gif不能正常顯示的問題(這里是iPhone 6s,iOS 12.4), 然后更換加載方式,使用騰訊的QMUIKit框架進(jìn)行加載,使用方法
- (UIImage *)qmui_animatedImageWithData:(NSData *)data scale:(CGFloat)scale
發(fā)現(xiàn)還是無法正常顯示, 于是查看了qmui_animatedImageWithData:(NSData *)data scale:(CGFloat)scale的實(shí)現(xiàn)源碼
- (UIImage *)qmui_animatedImageWithData:(NSData *)data scale:(CGFloat)scale {
// http://www.jianshu.com/p/767af9c690a3
// https://github.com/rs/SDWebImage
if (!data) {
return nil;
}
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
size_t count = CGImageSourceGetCount(source);
UIImage *animatedImage = nil;
if (count <= 1) {
animatedImage = [[UIImage alloc] initWithData:data];
} else {
NSMutableArray<UIImage *> *images = [[NSMutableArray alloc] init];
NSTimeInterval duration = 0.0f;
for (size_t i = 0; i < count; i++) {
CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
duration += [self qmui_frameDurationAtIndex:i source:source];
UIImage *frameImage = [UIImage imageWithCGImage:image scale:scale == 0 ? ScreenScale : scale orientation:UIImageOrientationUp];
[images addObject:frameImage];
CGImageRelease(image);
}
if (!duration) {
duration = (1.0f / 10.0f) * count;
}
animatedImage = [UIImage animatedImageWithImages:images duration:duration];
}
CFRelease(source);
return animatedImage;
}
查看了注釋中的簡書和github,最后采用如下方式加載
// #import "UIImageView+Gif.h" //給imageView添加category- (void)at_setGifImageWithGifFile:(NSString *)file animationDuration: (CGFloat)duration{NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:file withExtension: @"gif"]; //加載GIF圖片CGImageSourceRef gifSource = CGImageSourceCreateWithURL((CFURLRef) fileUrl, NULL); //將GIF圖片轉(zhuǎn)換成對(duì)應(yīng)的圖片源size_t frameCout = CGImageSourceGetCount(gifSource); //獲取其中圖片源個(gè)數(shù),即由多少幀圖片組成NSMutableArray *frames = [[NSMutableArray alloc] init]; //定義數(shù)組存儲(chǔ)拆分出來的圖片for (size_t i = 0; i < frameCout; i++) {CGImageRef imageRef = CGImageSourceCreateImageAtIndex(gifSource, i, NULL); //從GIF圖片中取出源圖片UIImage *imageName = [UIImage imageWithCGImage:imageRef]; //將圖片源轉(zhuǎn)換成UIimageView能使用的圖片源[frames addObject:imageName]; //將圖片加入數(shù)組中CGImageRelease(imageRef);}CFRelease(gifSource);self.animationImages = frames; //將圖片數(shù)組加入U(xiǎn)IImageView動(dòng)畫數(shù)組中self.animationDuration = duration; //每完成一次動(dòng)畫時(shí)長[self startAnimating]; //開啟動(dòng)畫}這樣使用在UITableView或者UICollection等列表中加載可能會(huì)出現(xiàn)問題,可嘗試以下方法解決
if (!<#imageView#>.isAnimating) {[<#imageView#> startAnimating]; }參考文檔:
簡書、github
總結(jié)
以上是生活随笔為你收集整理的iOS 加载本地Gif图片的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 深度学习(三)之LSTM写诗
- 下一篇: Lotto(DFS处理)