創(chuàng)建UIImage的方法有兩種:

? ? ?UIImage *image = [UIImageimageNamed:@"image.jpg"];//這種不釋放內(nèi)存,要緩存

? ? ?NSString *path = [[NSBundlemainBundle]pathForResource:@"image"ofType:@"jpg"];

? ? ?UIImage *image1 = [UIImageimageWithContentsOfFile:path];//這種會釋放內(nèi)存

? ? ?那么,為UIView添加背景圖片可以有三種方法:

? ? ?1.在UIView上添加一個UIImageView

? ? ?UIImageView *imageView = [[UIImageViewalloc]initWithFrame:self.view.bounds];

? ? ?imageView.image = [[UIImageimageNamed:@"image.jpg"]stretchableImageWithLeftCapWidth:10topCapHeight:10];

? ? ?[self.viewaddSubview:imageView];

? ? ?//這種方式,如果原始圖片不小不夠,則會拉伸以滿足View的尺寸,在View釋放之后沒有內(nèi)存保留。

? ? ?2.將圖片作為UIView的背景色

? ? ?//1.imageNamed方式

? ? ?self.view.backgroundColor = [UIColorcolorWithPatternImage:[UIImageimageNamed:@"image.jpg"]];

? ? ?//2.方式

? ? ?NSString *path = [[NSBundlemainBundle]pathForResource:@"image"ofType:@"jpg"];

? ? ?self.view.backgroundColor = [UIColorcolorWithPatternImage:[UIImageimageWithContentsOfFile:path]];

? ? ?//這兩種方式都會在生成color時占用大量的內(nèi)存。如果圖片大小不夠,就會平鋪多張圖片,不會去拉伸圖片以適應(yīng)View的大小。

? ? ?//在View釋放后,1中的color不會跟著釋放,而是一直存在內(nèi)存中;2中的color會跟著釋放掉,當然再次生成color時就會再次申請內(nèi)存。

3.其他方式(推薦)

? ? ?NSString *path = [[NSBundlemainBundle]pathForResource:@"image"ofType:@"jpg"];

? ? ?UIImage *image = [UIImageimageWithContentsOfFile:path];

? ? ?self.view.layer.contents = (id)image.CGImage;

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容