我是靠谱客的博主 完美月饼,这篇文章主要介绍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);

最后

以上就是完美月饼最近收集整理的关于iOS UIView添加背景图片的全部内容,更多相关iOS内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(44)

评论列表共有 0 条评论

立即
投稿
返回
顶部