更改UIView的背景加載圖片消耗內存比較

本文分析對比了各種更改UIView背景的方法。當然,背景是根據一個圖片來的(非純色)。

一.加一個uiimageview在uiview上面

複製代碼
    UIImageView* imageView = [[UIImageView alloc] initWithFrame:view.bounds];
    imageView.image = [[UIImage imageNamed:@"name.png"] stretchableImageWithLeftCapWidth:left topCapHeight:top];
    [view addSubview:imageView];
複製代碼

這種方式,如果原始圖片大小不夠(小於view的大小),可以拉伸,在view釋放後也沒有什麼內存保留。

二.通過圖片來生成UIColor設置view的backgroundColor

1.imageNamed方式

複製代碼
view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"name.png"]];
複製代碼

2.contentOfFile方式

複製代碼
NSString* path = [[NSBundle mainBundle] pathForResource:@"name" ofType:@"png"];
    view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:path];
複製代碼

這兩種方式都會在生成color時佔用大量的內存(原始圖片的n倍,這個n可能會達到幾千的程度)。而且如果圖片大小不夠,就會按照原始大小一個一個u畫過去,也就是不會自動拉伸。1和2的區別在於,view釋放後,1中的color並不會跟着釋放,而是一直存在於內存中(當然,再次根據這個圖片生成color時並不會再次申請內存了),而2中的color就會隨着view的釋放而釋放。

三.quartzCore方式

複製代碼
UIImage *image = [UIImage imageNamed:@"name.png"];
    view.layer.contents = (id) image.CGImage;
    // 如果需要背景透明加上下面這句
    view.layer.backgroundColor = [UIColor clearColor].CGColor;
複製代碼

這種方式會自動拉伸圖片,而且沒有額外內存佔用。

綜上,推薦第三種方式來根據圖片設置背景色。

發佈了79 篇原創文章 · 獲贊 74 · 訪問量 61萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章