[iOS]图片高清度太高, 导致内存过大Crash

先说一下状况, 后台提供的图片太高清了, 每个图片都在2-4MB, iOS上每个页面需要同时下载并展示10-15张.

这个时候, 如果我多滑动collectionView几次, 直接App就崩溃了(reason: 是内存警告, 超出每个App可用的最大内存限制)

 

解决方法: 经过各种百度, Google以后. 我是这样解决的. 缩小图片的高清度.

// 开辟一条子线程
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 { // Create a graphics image context UIGraphicsBeginImageContext (newSize); // Tell the old image to draw in this new context, with the desired // new size [image drawInRect : CGRectMake ( 0 , 0 ,newSize. width ,newSize. height )]; // Get the new image from the context UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext (); // End the context UIGraphicsEndImageContext (); // Return the new image. return newImage; }

 

posted on 2016-04-18 15:36  M_Lee  阅读(1844)  评论(1编辑  收藏  举报

导航