iOS UIView添加背景图片

在我们平时的开发中,有时需要给View设置一张图片做为背景。我们知道UIView是没有直接提供这样的API给我们的,我们可以另辟新径,达到这样的目的。

一、先简单说下用本地的图片创建UIImage的方式:

+ (nullable UIImage *)imageNamed:(NSString *)name;
+ (nullable UIImage *)imageWithContentsOfFile:(NSString *)path

这两种方式都可以创建一个UIImage实例,当然它们的区别还是有的。

  • 前者在创建UIImage对象时,系统会自动做了缓存,不会释放内存,适用于小型的图片。
  • 后者在创建UIImage对象时,系统不会做图片缓存,内存会立即释放,适用于大型的图片,如需要全屏的图片。

    UIImage *image1 = [UIImage imageNamed:@"image"];
    
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"jpg"];
    UIImage *image2 = [UIImage imageWithContentsOfFile:imagePath];

二、 UIView设置背景图片

1.在UIView上添加一个UIImageView

    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"jpg"];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    
    image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10) resizingMode:UIImageResizingModeStretch];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    imageView.image = image;
    [self.view addSubview:imageView];

2.将图片作为UIView的背景色

    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"jpg"];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:image];

3.其他方式(推荐)

    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"jpg"];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    
    self.view.layer.contents = (__bridge id _Nullable)(image.CGImage);

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值