IOS 多個UIImageView 載入高清大圖時記憶體管理

來源:互聯網
上載者:User

IOS 多個UIImageView 載入高清大圖時記憶體管理

當我們在某一個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]; //產生你想要尺寸的圖

 

 

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

 

 

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.