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



  • 相关阅读:
    python的继承、封装、多态 --面向对象的特征
    ab压测工具简介
    dotnet core Console事件处理机制
    屹立千年,只为你一个回眸
    Derivative of the Sigmoid function
    Merge Overlapping Intervals
    Array of products
    Longest Peak
    javascript事件的注册方式总结
    纯css实现圆柱体-超简单!
  • 原文地址:https://www.cnblogs.com/wangluochong/p/5555234.html
Copyright © 2020-2023  润新知