一 . 設置UIView的背景圖片
1.將圖片作為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時占用大量的內存。如果圖片大小不夠,就會平鋪多張圖片,不會去拉伸圖片以適應View的大小。
//在View釋放后,1中的color不會跟着釋放,而是一直存在內存中;2中的color會跟着釋放掉,當然再次生成color時就會再次申請內存
2.在UIView上再添加一個UIImageView顯示圖片作為UIView的背景圖片
注意:如果有點擊事件的話, userInteractionEnabled用戶交互設置為YES。
3.iOS視圖都是一個圖層,最先放置的圖層就會在最底層,如此最先給UIView添加一個UIImageView就可以作為UIView的背景圖片使用啦。
4.其他方式(推薦)
NSString *path = [[NSBundlemainBundle]pathForResource:@"image"ofType:@"jpg"];
UIImage *image = [UIImageimageWithContentsOfFile:path];
self.view.layer.contents = (id)image.CGImage;
//注意: 要寫清楚后綴,即使是”.png”。