您的位置:首页 > 其它

图片异步加载之SDWebImage

2013-11-30 12:18 232 查看
转自:http://blog.csdn.net/ryantang03/article/details/9263189

在开发中经常会遇到列表加载的功能,其中大部分都包括图片列表加载,但移动设备本身内存有限,而大量图片加载又很耗内存。今天主要就介绍一个第三方图片异步加载库SDWebImage,Github地址为:https://github.com/rs/SDWebImage,这个库主要实现了为UIImageView添加一个类别方法,让使用者使用图片异步加载就好像直接为UIImageView设置image一样,使用非常方便。

一、主要功能

An UIImageView category adding web image and cache management to the Cocoa Touch framework
An asynchronous image downloader
An asynchronous memory + disk image caching with automatic cache expiration handling
Animated GIF support
WebP format support
A background image decompression
A guarantee that the same URL won't be downloaded several times
A guarantee that bogus URLs won't be retried again and again
A guarantee that main thread will never be blocked
Performances!
Use GCD and ARC

包括图片异步下载器、内存和本地缓存、GIF支持、相同URL不会重复下载、不会阻塞UI线程等。

二、集成使用步骤

Download and unzip the last version of the framework from the download
page(下载framwork包并解压)
Right-click on the project navigator and select "Add Files to "Your Project":(右击工程选择添加库到项目工程)
In the dialog, select SDWebImage.framework:(选择SDWebImage.framwork库)
Check the "Copy items into destination group's folder (if needed)" checkbox(选择拷贝到工程复选框)
添加ImageIO.framework库支持
添加Linker Flag,如下图



按下Command+B,编译工程,如果编译成功则说明集成成功了,如果出现framwork找不到的异常,则将工程目录中SDWebImage-3.3.framwork改名为SDWebImage.framwork再编译就没问题了,由于我下的是最新3.3版本,可能原配置文件搜索的编译路径名是不带“-3.3”的,所以提一下这个问题。配置和编译成功后就可以开始使用了:

三、Demo实现
先看看最终实现的效果图,主要实现了UITableView的列表加载和单个图片的异步加载:








在需要使用异步图片加载的头文件导入:

#import <SDWebImage/UIImageView+WebCache.h>

列表实现在UITableView的协议方法中只需要很简单的调用UIImageView的类别方法即可完成异步加载:

[cpp] view
plaincopy

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

static NSString *Identifier = @"UITableViewIdentifier";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];

if (cell == nil) {

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier];

}



NSInteger row = indexPath.row;

cell.textLabel.text = @"My Text";

[cell.imageView setImageWithURL:[arr_imgs objectAtIndex:row]];



return cell;

}

单击UITableView的item进入单个图片加载页面,使用SDWebImageDownloader加载:

[cpp] view
plaincopy

//单独异步下载一个图片

[[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:self.imgURL] options:0 progress:^(NSUInteger receivedSize, long long expectedSize) {



} completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {

if (image && finished) {

imageView.image = image;

}

}];

以上只给出关键代码,具体Demo详情请下载工程源码:下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: