• [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; }
  • 相关阅读:
    SpringMVC+Apache Shiro+JPA(hibernate)
    Win7系统上配置使用Intellij Idea 13的SVN插件
    标志一个方法为过时方法
    Java模板引擎 HTTL
    Spring security与shiro
    墨刀 手机app原型工具
    java远程调试(断点)程序/tomcat( eclipse远程调试Tomcat方法)
    结合MongoDB开发LBS应用
    基于LBS的地理位置附近的搜索以及由近及远的排序
    discuz 发布分类信息,能不能设置单版块去掉“发帖子”(默认点发帖后为自定义的默认分类信息模版)
  • 原文地址:https://www.cnblogs.com/lidongxu/p/5404700.html
Copyright © 2020-2023  润新知