[iOS]图片高清度太高, 导致内存过大Crash
生活随笔
收集整理的這篇文章主要介紹了
[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;}
?
轉載于:https://www.cnblogs.com/lidongxu/p/5404700.html
總結
以上是生活随笔為你收集整理的[iOS]图片高清度太高, 导致内存过大Crash的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (转)搜索Maven仓库 获取 grou
- 下一篇: 个人工作总结01