SDWebImage的实现原理(UIImageView+WebCach)
1.作用:
SDWebImageView的功能很强大,其中UIImageView+WebCach.h的功能主要是下载图片,设置图片缓存.
2.原理:
下载图片的原理:通过图片的网站地址URL异步下载图片;
缓存图片的原理:下载完成的图片会被保存的内存和文件中;加载图片的时候首先会到内存中去找图片,如果没有就到文件中找,再没有才下载图片。
3.用法:
导入第三方库SDWebImage
头文件:UIImageView+webCache.h
主要语句:
[cell.posterImagesd_setImageWithURL:[NSURLURLWithString:album.poster]placeholderImage:[UIImagep_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=[UIImagep_w_picpathWithData:readData];}else{NSString*filePath=[selfgenerateFilePath:album.poster];NSData*dataFromFile=[NSDatadataWithContentsOfFile:filePath];if(dataFromFile){cell.p_w_picpathView.p_w_picpath=[UIImagep_w_picpathWithData:filePath];self.p_w_picpathMutableDic[album.poster]=dataFromFile;}else{//异步下载图片,主线程加载,正确//手动实现多级缓存(滑动的时候需要重新下载)[selfdownloadImageViewCell:cellwithAlbum:album];[dataFromFilewriteToFile:filePathatomically:YES];self.p_w_picpathMutableDic[album.poster]=dataFromFile;}}//异步下载图片的方法-(void)downloadImageViewCell:(MXTableViewCell*)cellwithAlbum:(MXAlbum*)album{dispatch_queue_tglobalQueue=dispatch_get_global_queue(0,0);dispatch_async(globalQueue,^{NSString*p_w_picpathStr=album.poster;NSURL*url=[NSURLURLWithString:p_w_picpathStr];NSData*p_w_picpathData=[NSDatadataWithContentsOfURL:url];dispatch_async(dispatch_get_main_queue(),^{cell.posterImage.p_w_picpath=[UIImagep_w_picpathWithData:p_w_picpathData];});});}//找文件的路径-(NSString*)generateFilePath:(NSString*)p_w_picpathURLStr{NSString*cachesPath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)firstObject];NSString*p_w_picpathName=[p_w_picpathURLStrlastPathComponent];return[cachesPathstringByAppendingPathComponent:p_w_picpathName];}
采用SDWebImage的方法
(1)导入三方库SDWebImage
(2)导入头文件
#import"UIImageView+WebCache.h"
(3)一句话搞定
[cell.posterImagesd_setImageWithURL:[NSURLURLWithString:album.poster]placeholderImage:[UIImagep_w_picpathNamed:@"s0"]];
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。