你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> IOS 多個UIImageView 加載高清大圖時內存管理

IOS 多個UIImageView 加載高清大圖時內存管理

編輯: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.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 image.

 

UIImage+Alpha.h, UIImage+Alpha.m
Extends 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]; //生成你想要尺寸的圖

 

 

造成的問題,要注意縮放的比例,不要導致圖片變形,由於尺寸縮小,可能會導致圖片模糊,注意縮小的尺寸。

 

 

綜上可見,每種方法有優點,有缺點。主要依據自己的開發情況,折中使用。

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved