先说一下状况, 后台提供的图片太高清了, 每个图片都在2-4MB, iOS上每个页面需要同时下载并展示10-15张.
这个时候, 如果我多滑动collectionView几次, 直接App就崩溃了(reason: 是内存警告, 超出每个App可用的最大内存限制)
解决方法: 经过各种百度, Google以后. 我是这样解决的. 缩小图片的高清度.
<pre>
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;[cachePath stringByAppendingPathComponent:@"imageCache"];
NSString *imagePath = [NSString stringWithFormat:@"%@/%d", cachePath, [self.theExhib.worksPic hash]];
NSFileManager *fileManager = [NSFileManager defaultManager];NSData *da = nil;
// 判断一下图片在本地在不在
if ([fileManager fileExistsAtPath:imagePath]) {
// 如果在, 直接就取
da = [NSData dataWithContentsOfFile:imagePath];
}else {
// 如果不在, 就重新下载(self.theExhib.worksPic是网址)
da = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.theExhib.worksPic]];
// 把图片流写入本地[da writeToFile:imagePath atomically:YES];
}
// 把NSData流转化成UIImage对象
UIImage *ima = [UIImage imageWithData:da];
// 调用自己的方法imageWithImageSimple scaldToSize: (Size后面填写的你要缩小成的图片分辨率)
ima = [self imageWithImageSimple:ima scaledToSize:CGSizeMake(100, 200)];
// 回到主线程刷新UI dispatch_async(dispatch_get_main_queue(), ^{[self.bacImageV setImage:ima];
});
});
- ( UIImage *)imageWithImageSimple:( UIImage *)image scaledToSize:( CGSize )newSize{
UIGraphicsBeginImageContext (newSize);
[image drawInRect : CGRectMake ( 0 , 0 ,newSize. width ,newSize. height )];
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext ();
UIGraphicsEndImageContext ();
return newImage;
}
</pre>
网友评论