iOS開發中有時候會將UIViewController或者UIView的subViews設置為透明,然后在底部設置背景圖片,我們常用加載圖片有UIImage的imageName和imageWithContentsOfFile兩個方法: [UIImage imageNamed:@"FlyElephant"] [UIImage imageWithContentsOfFile:@"FlyElephant"] 前者會對圖片進行緩存,第二種方法不會,如果圖片使用多次建議使用第一種方法,如果只使用一次建議使用第二種方式,設置UIView的背景圖片同樣有兩種方式: 1.設置UIImageView: UIImageView *imageView=[[UIImageView alloc]initWithFrame:self.view.bounds]; imageView.image=[UIImage imageNamed:@"FlyElephant"]; [self.view insertSubview:imageView atIndex:0]; 2.設置layer的content: UIImage *backGroundImage=[UIImage imageNamed:@"FlyElephant"]; self.view.contentMode=UIViewContentModeScaleAspectFill; self.view.layer.contents=(__bridge id _Nullable)(backGroundImage.CGImage); 有的時候可能需要一些毛玻璃效果,iOS8提供了UIVisualEffectView可以輕松實現毛玻璃效果: UIVisualEffectView *visualEfView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]]; visualEfView.frame =self.view.bounds; [imageView addSubview:visualEfView]; 援引作者:FlyElephant 鏈接:http://www.jianshu.com/p/d26a3d26e890
還有
一 . 設置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”。
援引:https://www.cnblogs.com/mancong/p/5013814.html?utm_source=tuicool&utm_medium=referral
self.view.layer.contents = (id)[UIImage imageNamed:@"你的背景圖片"].CGImage;
////////////////////////////////////////////////
////////////////////////////////////////////////
// 設置背景圖片
NSImageView *imageView=[[NSImageView alloc]initWithFrame:CGRectMake(0,64,GZDeviceWidth,GZDeviceHeight-108)];
imageView.image=[UIImage imageNamed:@"play_page_default_bg.jpg"];
[self.view insertSubview:imageView atIndex:0];
