sdwebimage gif支持gif么

利用SDWebImage加载gif - 博客频道 - CSDN.NET
aoxiangccp的博客
&* SDWebImage&加载gif图片
- (void)loadingGifImageView
& &NSString& *filePath = [[NSBundle&bundleWithPath:[[NSBundle&mainBundle]&bundlePath]]pathForResource:@&12345.gif&;&ofType:nil];
& &&NSData& *imageData = [NSData&dataWithContentsOfFile:filePath];
& &&if&(!self.gifImageView) {
& & & &&self.gifImageView&=
[[UIImageView&alloc]&init];
& &&self.gifImageView.backgroundColor&=
[UIColor&clearColor];
& &&self.gifImageView.image&=
[UIImage&sd_animatedGIFWithData:imageData];
& &&self.gifImageView.frame&=&CGRectMake(100,
100,&100, 100);
& & [self.view&addSubview:self.gifImageView];
& & [self.view&bringSubviewToFront:self.gifImageView];
aoxiangccp
排名:千里之外iphone开发之—网络与多线程(56)
具体如下所示:
$ git clone --recursive https:///rs/SDWebImage.git
1]如何防止一个url对应的图片重复下载
* &cell下载图片思路 –有沙盒缓存&
2] SDWebImage的默认缓存时长是多少?
3] SDWebImage底层是怎么实现的?
* 上课PPT的&cell下载图片思路 –有沙盒缓存&
2&常用方法
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedB
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock
completed:(SDWebImageCompletionBlock)completedB
3&内存处理:当app接收到内存警告时,SDWebImage做了什么? 在SDWebImageCache.m中可以找到
- SDWebImage会监听系统的UIApplicationDidReceiveMemoryWarningNotification通知,一旦收到通知,就会清理内存
- 应用程序将要终止的通知,UIApplicationWillTerminateNotification,清理磁盘
- 应用程序进入后台的通知,UIApplicationDidEnterBackgroundNotification,也会清理磁盘
4& SDWebImageOptions
* SDWebImageRetryFailed :下载失败后,会自动重新下载
* SDWebImageLowPriority :当正在进行UI交互时,自动暂停内部的一些下载操作
* SDWebImageRetryFailed | SDWebImageLowPriority :拥有上面2个功能
// 图片的格式
PNG: 无损压缩!压缩比较低。 PNG图片一般会JPG大。
- GPU解压缩的消耗非常小。解压缩的速度比较快,比较清晰,苹果推荐使用
JPG: 有损压缩!压缩比非常高!照相机使用。
- GPU解压缩的消耗比较大
GIF: 可动画的图片
BMP: (位图),没有任何压缩。几乎不用
&关于SDwebImage中枚举参数options有以下几种,用到时可以查阅
&留待查阅&
typedefNS_OPTIONS(NSUInteger, SDWebImageOptions) {
* By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying.
* 默认情况下,当一个 URL下载失败,会将该 URL放在黑名单中,不再尝试下载
* This flag disable this blacklisting.
* 此标记取消黑名单
SDWebImageRetryFailed =1 &&0,
* By default, image downloads are started during UI interactions, this flags disable this feature,
* 默认情况下,在 UI交互时也会启动图像下载,此标记取消这一特性
* leading to delayed download on UIScrollView deceleration for instance.
* 会推迟到滚动视图停止滚动之后再继续下载(这个注释是假的!)
SDWebImageLowPriority =1 &&1,
* This flag disables on-disk caching
* 此标记取消磁盘缓存,只有内存缓存
SDWebImageCacheMemoryOnly =1 &&2,
* This flag enables progressive download, the image is displayed progressively during download as a browser would do.
* 此标记允许渐进式下载,就像浏览器中那样,下载过程中,图像会逐步显示出来
* By default, the image is only displayed once completely downloaded.
* 默认情况下,图像会在下载完成后一次性显示
SDWebImageProgressiveDownload =1 &&3,
* Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed.
* 即使图像被缓存,遵守 HTPP响应的缓存控制,如果需要,从远程刷新图像
* The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation.
* 磁盘缓存将由 NSURLCache处理,而不是 SDWebImage,这会对性能有轻微的影响
* This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics.
* 此选项有助于处理同一个请求 URL的图像发生变化
* If a cached image is refreshed, the completion block is called once with the cached image and again with the final image.
* 如果缓存的图像被刷新,会调用一次 completion block,并传递最终的图像
* Use this flag only if you can't make your URLs static with embeded cache busting parameter.
* 仅在无法使用嵌入式缓存清理参数确定图像 URL时,使用此标记
SDWebImageRefreshCached =1 &&4,
* In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for
* 在 iOS 4+,当 App进入后台后仍然会继续下载图像。这是向系统请求额外的后台时间以保证下载请求完成的
* extra time in background to let the request finish. If the background task expires the operation will be cancelled.
* 如果后台任务过期,请求将会被取消
SDWebImageContinueInBackground =1 &&5,
* Handles cookies stored in NSHTTPCookieStore by setting
* 通过设置
* NSMutableURLRequest.HTTPShouldHandleCookies = YES;
* 处理保存在 NSHTTPCookieStore中的 cookies
SDWebImageHandleCookies =1 &&6,
* Enable to allow untrusted SSL ceriticates.
* 允许不信任的 SSL证书
* Useful for testing purposes. Use with caution in production.
* 可以出于测试目的使用,在正式产品中慎用
SDWebImageAllowInvalidSSLCertificates =1 && 7,
* By default, image are loaded in the order they were queued. This flag move them to
* 默认情况下,图像会按照在队列中的顺序被加载,此标记会将它们移动到队列前部立即被加载
* the front of the queue and is loaded immediately instead of waiting for the current queue to be loaded (which
* 而不是等待当前队列被加载,等待队列加载会需要一段时间
* could take a while).
SDWebImageHighPriority =1 &&8,
* By default, placeholder images are loaded while the image is loading. This flag will delay the loading
* 默认情况下,在加载图像时,占位图像已经会被加载。而此标记会延迟加载占位图像,直到图像已经完成加载
* of the placeholder image until after the image has finished loading.
SDWebImageDelayPlaceholder =1 &&9,
* We usually don't call transformDownloadedImage delegate method on animated images,
* 通常不会在可动画的图像上调用 transformDownloadedImage代理方法,因为大多数转换代码会破坏动画文件
* as most transformation code would mangle it.
* Use this flag to transform them anyway.
* 使用此标记尝试转换
SDWebImageTransformAnimatedImage =1 &&10,
SDWebImage播放GIF
ViewController.m
SDWebImage播放GIF
Created by apple on 15/10/25.
Copyright (c) 2015年 LiuXun. All rights reserved.
#import &ViewController.h&
#import &UIImageView+WebCache.h&
#import &UIImage+GIF.h&
@interface ViewController ()
@property(nonatomic, strong) UIImageView *imageVI
@implementation ViewController
-(void)viewDidLoad
self.imageVIew = [[UIImageView alloc] initWithFrame:self.view.bounds ];
[self.view addSubview:self.imageVIew];
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
[self.imageVIew sd_setImageWithURL:[[NSBundle mainBundle] URLForResource:@&bd698b0fjw1e0ph8unyg6g.gif& withExtension:nil]];
PNG: 无损压缩! 压缩程度没有JPG高。PNG图片一般比JPG大,比较清晰,解压速度比较快, GPU解压消耗比较小,苹果推荐使用。
JPG:有损压缩!压缩比非常高!照相机使用 GPU压缩的消耗比较大
GIF: 可动画的图片
BMP: 位图 没有任何压缩,无论如何放大都不会失真。开发中一般不使用。
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:145846次
积分:4887
积分:4887
排名:第4875名
原创:349篇
转载:24篇
评论:21条
(8)(11)(5)(1)(1)(1)(18)(21)(9)(7)(7)(2)(6)(17)(64)(44)(68)(38)(2)(2)(24)(17)SDWebImage 对多gif显示内存消耗过高的优化 - 简书
SDWebImage 对多gif显示内存消耗过高的优化
项目中有时候会遇到当前页面用到大量gif的情况,这个时候如果仅仅用SDWebImage去加载gif的话,会出现内存暴增的现象.
这是因为 SD在对 gif 的处理过程中采用了一个数组存储 gif 的帧图片,当有大量动态图时,大量图片存在内存中,造成了内存暴增的现象.
先看SDWebImage的源代码,SDWebImage通过这个类UIImage+GIF.h来处理gif,我们进入头文件发现会调用一个+ (UIImage *)sd_animatedGIFWithData:(NSData *)data 这样的类方法下面是这个方法的源代码,我已经加了很详细的注释,并且把问题的所在也写的很清楚.
+ (UIImage *)sd_animatedGIFWithData:(NSData *)data {
//安全判断
if (!data) {
//二进制类型的转换
//CGImageSourceRef是个什么呢? 我们可以看到这是一个typedef CGImageSource * CGImageSourceR
//这是一个指针,CGImageSource是对图像数据读取任务的抽象,通过它可以获得图像对象、缩略图、图像的属性(包括Exif信息)。
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
//获取有几张图片
size_t count = CGImageSourceGetCount(source);
//返回的动态图片
UIImage *animatedI
//如果为一张图片,那就只显示一张图片
if (count &= 1) {
animatedImage = [[UIImage alloc] initWithData:data];
//如果为多张图片,就开始创建动态图片
//集合 存放单张的图片
NSMutableArray *images = [NSMutableArray array];
NSTimeInterval duration = 0.0f;
for (size_t i = 0; i & i++) {
//取出gif单张的图片
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) *
//把静态的图片转换为动态的image,所以会有大量单张的图片存放在内存中
animatedImage = [UIImage animatedImageWithImages:images duration:duration];
//释放图像数据读取任务的抽象对象
CFRelease(source);
//返回动态图片
return animatedI
gif播放其实就是一张一张图片返回去,我们要写一个方法,只要不断地取出当前的那一张图片,这样就可以有效的避免内存中存储了大量图片.那如何实现不断地去取呢,我们可以开一个定时器,定时器不断的去掉我们写的方法,不断地去取图片赋值给imageView.
我采用创建一个UIImageView子类来封装定时器方法.
需要注意导入相关的头文件&ImageIO/ImageIO.h&.
这个方法的本质就是用一个定时器不断的去获取一张图片给imageView,这样就避免了大量图片存入内存中.
附上github源码,懒得下的人,源码就在下面.我也写了很详细的注释.
实例代码中,在一个界面上用了6个gif,如果用原生的方法,内存会达到130M左右,如果采用计时器方法,则只有30M左右
#import "WBWebImage.h"
#import &SDWebImageManager.h&
#import &NSData+ImageContentType.h&
#import &UIImage+GIF.h&
#import &ImageIO/ImageIO.h&
@implementation WBWebImage {
//记录当前是第几张gif
NSInteger _currentI
NSTimer *_
//gif图片的二进制数据
//1.根据url去下载图片的二进制数据
//2.根据图片的类型判断如果是gif特殊处理
//3.如果是其他类型,直接显示
- (void)WB_downloadIMGOrGif:(NSURL *)url {
_timer = [NSTimer timerWithTimeInterval:0.12 target:self selector:@selector(updateIMG) userInfo:nil repeats:YES];
[self downloadIMGData:url];
- (void)updateIMG {
//不断的调用生成gif的方法,并且不断的赋值给imageView
self.image = [self wb_animatedGIFWithData:_data];
//下载图片
- (void)downloadIMGData:(NSURL *)url {
//从管理者进行查找
[[SDWebImageManager sharedManager].imageDownloader downloadImageWithURL:url options:0 progress:nil completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
if (error) {
NSLog(@"下载错误%@",error);
//根据图片的类型进行判断;
//UI操作放在主线程
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
if ([[NSData sd_contentTypeForImageData:data] isEqualToString:@"image/gif"]) {
//据图片的类型判断如果是gif特殊处理
//将定时器加入到运行循环中
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
self.image =
//原始代码是把所有的gif全部加载处理完毕才去播放,内存占用过多
//修改: 开启一个定时器,不断的去gif中取出对应的单张图片
- (UIImage *)wb_animatedGIFWithData:(NSData *)data {
if (!data) {
//类型转换
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
//几张图片
size_t count = CGImageSourceGetCount(source);
//返回的变量
UIImage *animatedI
if (count &= 1) {
animatedImage = [[UIImage alloc] initWithData:data];
//取出gif中的单张图片
CGImageRef image = CGImageSourceCreateImageAtIndex(source, _currentIndex % count, NULL);
_currentIndex ++;
//类型的转换
animatedImage = [UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];
CGImageRelease(image);
CFRelease(source);
return animatedI
利用定时器方法,会稍微增加一些cpu的负荷,原因是cpu不断的再计算.
利用图片数组来做gif,虽然cpu轻松了,但是内存负荷大.
两个方法,一个是用性能去换空间,一个是用空间换性能.
一个大彻大悟总比别人晚两年的人SDWebImage 源码分析 --加载gif图片
时间: 18:05:51
&&&& 阅读:7398
&&&& 评论:
&&&& 收藏:0
标签:&&&&&&&&&&&&&&&&&&&&&&&&&&&n年关了,马上放假,终于把手头上的事情告一段落,连续发布了3个app,我也是醉了。
终于有了点时间。想研究下SDWebImage是怎么加载gif图片的。
一直很好奇。
现在开始。
1,首先我们看下SDWebImage是怎么加载gif的。
faceButton.image = [UIImage sd_animatedGIFNamed:[NSString stringWithFormat:@"CHATA_%d",i - 46]];
sd_animatedGIFNamed是SDWebImage提供的加载gif图片的一种方法。我们点进去这个方法去看以下。2,sd_animatedGIFNamed 这个方法的实现如下。生成一个UIImage对象。
+ (UIImage *)sd_animatedGIFNamed:(NSString *)name {
//取到屏幕分辨率
CGFloat scale = [UIScreen mainScreen].
//是否是高清屏
if (scale & 1.0f) {
//如果是高清屏
//读取图片
NSString *retinaPath = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"gif"];
//图片转换为data
NSData *data = [NSData dataWithContentsOfFile:retinaPath];
//如果图片存在
if (data) {
//调用sd_animatedGIFWithData 生成image实例
return [UIImage sd_animatedGIFWithData:data];
读取普通图片
NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];
//图片转换为data
data = [NSData dataWithContentsOfFile:path];
//如果图片存在
if (data) {
//调用sd_animatedGIFWithData 生成image实例
return [UIImage sd_animatedGIFWithData:data];
//如果图片不存在
return [UIImage imageNamed:name];
//如果不是高清屏 读取普通图片
NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];
//图片转换为data
NSData *data = [NSData dataWithContentsOfFile:path];
//如果图片存在
if (data) {
//调用sd_animatedGIFWithData 生成image实例
return [UIImage sd_animatedGIFWithData:data];
//如果图片不存在
return [UIImage imageNamed:name];
注释已经很详细了,这个类方法里面主要是确定当前设备的分辨率,以便加载不同分辨率的图片。然后通过
dataWithContentsOfFile方法把图片转换为NSData,判断NSData是否存在。如果存在调用sd_animatedGIFWithData 后续处理。3,sd_animatedGIFWithData 方法。
+ (UIImage *)sd_animatedGIFWithData:(NSData *)data {
if (!data) {
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
size_t count = CGImageSourceGetCount(source);
UIImage *animatedI
if (count &= 1) {
animatedImage = [[UIImage alloc] initWithData:data];
NSMutableArray *images = [NSMutableArray array];
NSTimeInterval duration = 0.0f;
for (size_t i = 0; i & i++) {
CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
duration += [self frameDurationAtIndex:i source:source];
[images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];
CGImageRelease(image);
if (!duration) {
duration = (1.0f / 10.0f) *
animatedImage = [UIImage animatedImageWithImages:images duration:duration];
CFRelease(source);
return animatedI
  先看这行代码
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
CGImageSourceRef定义如下,
  typedef struct CGImageSource *CGImageSourceR
可以看到它是一个CGImageSource 指针。
CGImageSource又是什么呢?
CGImageSource是对图像数据读取任务的抽象,通过它可以获得图像对象、缩略图、图像的属性(包括Exif信息)。
那么这行代码可以这样理解:通过nadata取到图像的以系列信息。
size_t count = CGImageSourceGetCount(source);
这行代码是读取CGImageSourceRef有几个图片对象。
next,下面就不难理解了,
CGImageSourceCreateImageAtIndex 从
source里面读取各个图片放入数组里面。
读取显示图片的 时间。
duration += [self frameDurationAtIndex:i source:source];
4,计算图片显示时间
+ (float)frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source {
float frameDuration = 0.1f;
CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil);
NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameP
NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary];
NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
if (delayTimeUnclampedProp) {
frameDuration = [delayTimeUnclampedProp floatValue];
NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime];
if (delayTimeProp) {
frameDuration = [delayTimeProp floatValue];
if (frameDuration & 0.011f) {
frameDuration = 0.100f;
CFRelease(cfFrameProperties);
return frameD
详细分析 待续!!!5,
animatedImage = [UIImage animatedImageWithImages:images duration:duration];
播放数组里里面的图片。
over!!!!
标签:&&&&&&&&&&&&&&&&&&&&&&&&&&&原文:/yunis/p/4290666.html
&&国之画&&&& &&&&&&
&& &&&&&&&&&&&&&&
鲁ICP备号-4
打开技术之扣,分享程序人生!}

我要回帖

更多关于 sdwebimage 支持gif 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信