iOS 中 为UIView添加背景图片

本文介绍了在iOS开发中为UIView设置背景图片的三种方法,并详细对比了不同方法在内存使用及图片展示效果上的区别。

创建UIImage的方法有两种:

 

    UIImage *image = [UIImageimageNamed:@"image.jpg"];//这种不释放内存,要缓存

    

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

   UIImage *image1 = [UIImageimageWithContentsOfFile:path];//这种会释放内存


那么,为UIView添加背景图片可以有三种方法:

1.在UIView上添加一个UIImageView

 

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

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

    [self.viewaddSubview:imageView];

   //这种方式,如果原始图片不小不够,则会拉伸以满足View的尺寸,在View释放之后没有内存保留。


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时占用大量的内存。如果图片大小不够,就会平铺多张图片,不会去拉伸图片以适应View的大小。

   //在View释放后,1中的color不会跟着释放,而是一直存在内存中;2中的color会跟着释放掉,当然再次生成color时就会再次申请内存。

3.其他方式(推荐)

 

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

    

   UIImage *image = [UIImageimageWithContentsOfFile:path];

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



转载于:https://www.cnblogs.com/wangluochong/p/5555234.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值