SDWebImage播放GIF存在的问题,以及解决办法
2017-03-03 本文已影响1213人
佛祖求胖
在使用SDWebImage加载GIF,当滑动加载更多的cell时,内存暴涨.问题出现的图如下:
![](https://img.haomeiwen.com/i3153383/a7d74a8034a3a619.png)
从上图可以看出,当滑动cell ,加载数据时,内存近似直线的上升.
什么原因照成的呢?
1 查看SDWebImage加载GIF核心文件
CGImageSourceRef source =CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
// 获得GIF的 动图的帧数
size_t count = CGImageSourceGetCount(source);
UIImage *animatedImage;
// 帧数是1 直接返回静态图像
if (count <= 1) {
animatedImage = [[UIImage alloc] initWithData:data];
}
else {
// 创建图像数组 (每一次读取gif都会进行创建) 消耗性能的根源!
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;
2 解决方法
思路
1. 开启一个刷屏计时器,CADisplayLink
2. 每次触发,递增 index 只加载一桢图像!之前的图像立即释放!
使用YY_WebImage 能够很好的解决
UIImageView为 YYAnimatedImageView 这个类即可.
然后代码直接调用
头文件引用
#import "UIImageView+YYWebImage.h"
[self.WAU_pic_imageView setImageWithURL:model.image2 placeholder:[UIImage imageNamed:@"chat_item_file"]];
按照上面所述,得到的结果如下:
![](https://img.haomeiwen.com/i3153383/fe1cab84481f157f.png)
很明显可以看出,内存增加比较平缓,内存使用率也在可允许范围