UIView背景圖片設置一些技巧

一、加一個UIImageview在UIView上(可以)

UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    imageView.image = [UIImage imageNamed:@"home"];
    [self.view addSubview:imageView];
這種方式,原始圖片大小不夠(小於view的大小),會拉伸圖片,讓圖片失真,view釋放後也不會有什麼內存保留。


二、通過圖片來生成UIColor來設置UIView的背景色。注意是根據圖片來生成color(不推薦)

1.imageName方式:

self.view.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"home"]];

2.contentOfFile方式:

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

以上兩種方式都會在生成color的時候消耗大量的內存(原始圖片的N倍,這個N可能會達到幾千的程度,而且如果原始圖片大小不夠,就會按照原始大小一個一個U畫過去,是不會自動拉伸的。1和2的區別:1中的color不會隨着View的釋放而釋放,而是一直存在於內存中。(再次根據這個圖片生成Color的時候,不會再次去申請內存)。而2中的color會隨着View的釋放而釋放。


三、quarCore方式(推薦)

UIImage *image = [UIImage imageNamed:@"home"];
    //推薦這樣創建image對象:UIImage *image = [UIImage imageWithContentsOfFile:path];
    self.view.layer.contents = (id)image.CGImage;
    //背景透明加上這一句
    self.view.layer.backgroundColor = [UIColor clearColor].CGColor;


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