1.作用:
SDWebImageView的功能很强大,其中UIImageView+WebCach.h的功能主要是下载图片,设置图片缓存.
2.原理:
下载图片的原理:通过图片的网站地址URL异步下载图片;
缓存图片的原理:下载完成的图片会被保存的内存和文件中;加载图片的时候首先会到内存中去找图片,如果没有就到文件中找,再没有才下载图片。
3.用法:
导入第三方库SDWebImage
头文件:UIImageView+webCache.h
主要语句:
[cell.posterImage sd_setImageWithURL:[NSURL URLWithString:album.poster]placeholderImage:[UIImage imageNamed:@"s0"]];
4.例子:使用album中的图片地址字符串,加载图片到UITableViewCell上。
不用SDWebImageView的方法:
@property(nonatomic,strong)NSMutableDictionary *imageMutableDic;
NSData *readData = self.imageMutableDic[album.poster];
if(readData)
{
cell.posterImage.image = [UIImage imageWithData:readData];
}
else
{
NSString *filePath = [self generateFilePath:album.poster];
NSData *dataFromFile = [NSData dataWithContentsOfFile:filePath];
if(dataFromFile)
{
cell.imageView.image = [UIImage imageWithData:filePath];
self.imageMutableDic[album.poster] = dataFromFile;
}
else
{
//异步下载图片,主线程加载,正确
//手动实现多级缓存(滑动的时候需要重新下载)
[self downloadImageViewCell:cell withAlbum:album];
[dataFromFile writeToFile:filePath atomically:YES];
self.imageMutableDic[album.poster] = dataFromFile;
}
}
//异步下载图片的方法
- (void)downloadImageViewCell:(MXTableViewCell*)cell withAlbum:(MXAlbum *)album
{
dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
dispatch_async(globalQueue, ^{
NSString *imageStr = album.poster;
NSURL *url = [NSURL URLWithString:imageStr];
NSData *imageData = [NSData dataWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
cell.posterImage.image = [UIImage imageWithData:imageData];
});
});
}
//找文件的路径
- (NSString *)generateFilePath:(NSString *)imageURLStr
{
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];
NSString *imageName = [imageURLStr lastPathComponent];
return [cachesPath stringByAppendingPathComponent:imageName];
} 采用SDWebImage的方法
(1)导入三方库SDWebImage
(2)导入头文件
#import "UIImageView+WebCache.h"
(3)一句话搞定
[cell.posterImage sd_setImageWithURL:[NSURL URLWithString:album.poster]placeholderImage:[UIImage imageNamed:@"s0"]];
SDWebImage的实现原理(UIImageView+WebCach)
原文地址:http://11745402.blog.51cto.com/11735402/1790861