温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

IOS 多个UIImageView 加载高清大图时内存管理

发布时间:2020-07-12 22:15:55 来源:网络 阅读:513 作者:卓行天下 栏目:移动开发

IOS 多个UIImageView 加载高清大图时内存管理

 当我们在某一个View  多个UIImageView,且UIImageView都显示的是高清大图,就有可能出现内存警告的问题。如果第一次进入这个view,没有发生内存警告,当再次进入这个view,如果上一次的内存没有及时释放,这一次次的累加,便可导致内存崩溃。


1,UIImage 加载图片的方式。

      如果是本地图片,尽量不要使用 [UIImage  p_w_picpathNamed:nil]; 这种方式,如果使用这种方式加载,只要程序不退出,它便一直会在内存中。

     我们可以使用 :

                        NSString *path = [[NSBundlemainBundle]pathForResource:@'"图片的名字" ofType:@""];

                        UIImage *p_w_picpath = [UIImagep_w_picpathWithContentsOfFile:path];


         那两者的优缺点就很明显了,[UIImage  p_w_picpathNamed:nil]; 只需加载一次,它便在内存中,所以第二次加载速度很快。而第二种加载方式由于我们将它释放掉了,会再次加载。所以选用那种方式,依你情况而定。


2,上面说的第二种方式,虽然可以释放掉,但我们要告诉人家什么时候释放。也就是说,当前显示页面不是这个view时,我们便将它释放掉:

- (void)viewWillDisappear:(BOOL)animated{

    [UIImageView removeFromSuperview];

    UiImageView = nil;

}


当然,当我们再次进入这个view时,便要将移除掉的view再次添加进来


- (void)viewDidAppear:(BOOL)animated{

   [self addSubView:UIImageView];

}


3,上述两种方式,主要解决内存累加的问题。但如果第一次进入view,图片全部渲染在view上时,内存就崩溃了。那我们只能在图片上做文章了。我们加载的高清大图如果差不多都是3000*2000,也可能比这个还大,就算我们的程序是iPad App,iPad 4  的分辨率才多少,这些图远远大于设备的分辨率,完全是资源浪费,所以我们通常的一个做法,便是将这样的图以小尺寸渲染到view上。


推荐使用:


  • UIImage+Resize.h, UIImage+Resize.m

  • Extends the UIImage class to support resizing (optionally preserving the original aspect ratio), cropping, and generating thumbnails.


  • UIImage+RoundedCorner.h, UIImage+RoundedCorner.m

  • Extends the UIImage class to support adding rounded corners to an p_w_picpath.


  • UIImage+Alpha.h, UIImage+Alpha.m

  • Extends the UIImage class with helper methods for working with alpha layers (transparencies).


常用方法:


 UIImage *p_w_picpath 

 UIImage *thumbImage = [p_w_picpaththumbnailImage:140// This should the size of the view in collection view. example: myCell width is 20 and height is 20.

                                      transparentBorder:0

                                          cornerRadius:0

                                   interpolationQuality:kCGInterpolationMedium];       //生成缩略图




            // this "resizedp_w_picpath" p_w_picpath is what you want to pass to setImage

            UIImage * resizedImage = [p_w_picpathresizedImage:p_w_picpathview.frame.sizeinterpolationQuality:kCGInterpolationLow];   //生成你想要尺寸的图



    造成的问题,要注意缩放的比例,不要导致图片变形,由于尺寸缩小,可能会导致图片模糊,注意缩小的尺寸。



   综上可见,每种方法有优点,有缺点。主要依据自己的开发情况,折中使用。


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI