iOS 背景图片设置

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];




 

posted on 2017-12-07 10:37  高彰  阅读(3689)  评论(0编辑  收藏  举报

导航