一般加载iOS得网络图片用的很好的第三方框架是SDWebImage,然后我们会有一种点击查看大图得需求。一般这种需求接口会返回两种字段,一种是压缩图片地址A。一种是原图地址B。
那么问题就来了,一般用原图地址加载图片出来后,图片会有一定比例得失真。(我感觉没有问题,通常就是查看大图会加载原图地址。可是人家说了咱们的解决,那么怎么解决呢。)我发现给原图下载下来后在加载出来,没有问题。(我感觉都一样。)
话不多说,直接上代码
1、检测本地是否下载过改图片
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) objectAtIndex:0];
NSString *path = [cachesPath stringByAppendingString:[NSString stringWithFormat:@"/%lu.%@",(unsigned long)[url hash],url.pathExtension]];
NSData *data = [NSData dataWithContentsOfFile:path];
if (data == nil) {//需要下载
[self writeToCacheWithUrl:url];
}
//下载到本地
- (void)writeToCacheWithUrl:(NSString *)url {
dispatch_queue_t quest = dispatch_queue_create("down", DISPATCH_QUEUE_SERIAL);
dispatch_async(quest, ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
//创建文件管理器
NSFileManager *fileManager = [NSFileManager defaultManager];
//获取document路径
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
[fileManager createDirectoryAtPath:[cachesPath stringByAppendingString:@"/Caches"] withIntermediateDirectories:YES attributes:nil error:nil];
//写入路径
NSString *path = [cachesPath stringByAppendingString:[NSString stringWithFormat:@"/%lu.%@",(unsigned long)[url hash],url.pathExtension]];
[data writeToFile:path atomically:YES];
});
}
开个分线程,缓存到本地,然后从本地取出来,编码一下,然后再绘制出来。不知道这么处理是否真的与原来的直接加载的那种处理清晰度不一样。
2、取出来,重新绘制
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) objectAtIndex:0];
NSString *path = [cachesPath stringByAppendingString:[NSString stringWithFormat:@"/%lu.%@",(unsigned long)[imageUrl hash],imageUrl.pathExtension]];
NSData *data = [NSData dataWithContentsOfFile:path];
if (data == nil) {
[MBProgressHUD mj_showError:@"正在下载,请稍候"];
return;
}
UIImage *result = [UIImage imageWithData:data];
网友评论