iOS UIView 添加背景图片

114 阅读1分钟

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

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

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

以上两个方法都可以创建一个 UIImage 实例,但不同的是:

  • 前者在创建 UIImage 对象时,系统会自动缓存它,不会释放内存,适用于小型的图片。
  • 后者在创建 UIImage 对象时,系统不会做图片缓存,内存会立即释放,适用于不常用的大型图片,如需要全屏的图片。
    // 使用方法 `-imageNamed:` 创建 UIImage 实例
    UIImage *image1 = [UIImage imageNamed:@"bg_img"];
    
    // 使用方法 `-imageWithContentsOfFile:` 创建 UIImage 实例
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"bg_img" 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];
  1. 将图片作为 UIView 的背景色:
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"jpg"];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    self.view.backgroundColor = [UIColor colorWithPatternImage:image];
  1. 通过 UIViewlayer.contents 属性(推荐)
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"jpg"];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    self.view.layer.contents = (__bridge id _Nullable)(image.CGImage);