IOS 多个UIImageView 加载高清大图时内存管理_移动开发_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > 移动开发 > IOS 多个UIImageView 加载高清大图时内存管理

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

 2014/8/27 11:18:40  chenniuyi  程序员俱乐部  我要评论(0)
  • 摘要:当我们在某一个View多个UIImageView,且UIImageView都显示的是高清大图,就有可能出现内存警告的问题。如果第一次进入这个view,没有发生内存警告,当再次进入这个view,如果上一次的内存没有及时释放,这一次次的累加,便可导致内存崩溃。1,UIImage加载图片的方式。如果是本地图片,尽量不要使用[UIImageimageNamed:nil];这种方式,如果使用这种方式加载,只要程序不退出,它便一直会在内存中。我们可以使用
  • 标签:view imageView iOS 内存管理 内存

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

1,UIImage 加载图片的方式。
      如果是本地图片,尽量不要使用 [UIImage  imageNamed:nil]; 这种方式,如果使用这种方式加载,只要程序不退出,它便一直会在内存中。
     我们可以使用 :
                      NSString *path = [[NSBundlemainBundle]pathForResource:@'"图片的名字" ofType:@""];
                        UIImage *image = [UIImageimageWithContentsOfFile:path];

   那两者的优缺点就很明显了,[UIImage  imageNamed: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.mExtends the UIImage class to support resizing (optionally preserving the original aspect ratio), cropping, and generating thumbnails.
UIImage+RoundedCorner.h, UIImage+RoundedCorner.mExtends the UIImage class to support adding rounded corners to an image.
UIImage+Alpha.h, UIImage+Alpha.mExtends the UIImage class with helper methods for working with alpha layers (transparencies).

常用方法:
UIImage *image 

UIImage *thumbImage = [imagethumbnailImage: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 "resizedimage" image is what you want to pass to setImage
            UIImage * resizedImage = [imageresizedImage:imageview.frame.sizeinterpolationQuality: kCGInterpolationLow];   //生成你想要尺寸的图


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


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

详细说明:http://ios.662p.com/thread-2054-1-1.html

发表评论
用户名: 匿名