iOS-UIView-設定背景圖片4種方式,iosuiview背景圖片
一 . 設定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”。