1.作用:
SDWebImageView的功能很强大,其中UIImageView+WebCach.h的功能主要是下载图片,设置图片缓存.
2.原理:
下载图片的原理:通过图片的网站地址URL异步下载图片;
缓存图片的原理:下载完成的图片会被保存的内存和文件中;加载图片的时候首先会到内存中去找图片,如果没有就到文件中找,再没有才下载图片。
3.用法:
导入第三方库SDWebImage
头文件:UIImageView+webCache.h
主要语句:
[cell.posterImage sd_setImageWithURL:[NSURL URLWithString:album.poster]placeholderImage:[UIImage p_w_picpathNamed:@"s0"]];
4.例子:使用album中的图片地址字符串,加载图片到UITableViewCell上。
不用SDWebImageView的方法:
@property(nonatomic,strong)NSMutableDictionary *p_w_picpathMutableDic;
NSData *readData = self.p_w_picpathMutableDic[album.poster];
if(readData)
{
cell.posterImage.p_w_picpath = [UIImage p_w_picpathWithData:readData];
}
else
{
NSString *filePath = [self generateFilePath:album.poster];
NSData *dataFromFile = [NSData dataWithContentsOfFile:filePath];
if(dataFromFile)
{
cell.p_w_picpathView.p_w_picpath = [UIImage p_w_picpathWithData:filePath];
self.p_w_picpathMutableDic[album.poster] = dataFromFile;
}
else
{
//异步下载图片,主线程加载,正确
//手动实现多级缓存(滑动的时候需要重新下载)
[self downloadImageViewCell:cell withAlbum:album];
[dataFromFile writeToFile:filePath atomically:YES];
self.p_w_picpathMutableDic[album.poster] = dataFromFile;
}
}
//异步下载图片的方法
- (void)downloadImageViewCell:(MXTableViewCell*)cell withAlbum:(MXAlbum *)album
{
dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
dispatch_async(globalQueue, ^{
NSString *p_w_picpathStr = album.poster;
NSURL *url = [NSURL URLWithString:p_w_picpathStr];
NSData *p_w_picpathData = [NSData dataWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
cell.posterImage.p_w_picpath = [UIImage p_w_picpathWithData:p_w_picpathData];
});
});
}
//找文件的路径
- (NSString *)generateFilePath:(NSString *)p_w_picpathURLStr
{
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];
NSString *p_w_picpathName = [p_w_picpathURLStr lastPathComponent];
return [cachesPath stringByAppendingPathComponent:p_w_picpathName];
}
采用SDWebImage的方法
(1)导入三方库SDWebImage
(2)导入头文件
#import "UIImageView+WebCache.h"
(3)一句话搞定
[cell.posterImage sd_setImageWithURL:[NSURL URLWithString:album.poster]placeholderImage:[UIImage p_w_picpathNamed:@"s0"]];
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。