How do you make a background image scale to screen size in swift?

前端 未结 9 2086
刺人心
刺人心 2020-11-27 04:27

I\'m trying to make a UIView image for my background in swift using pattern image. The code I have works well except for the fact that I want the image to take the whole scr

相关标签:
9条回答
  • 2020-11-27 05:06

    Ahmad Fayyas Solution in Swift 3.0:

    func addBackground() {
        let width = UIScreen.main.bounds.size.width
        let height = UIScreen.main.bounds.size.height
    
        let imageViewBackground = UIImageView(frame: CGRect(x:0, y:0, width: width, height: height))
        imageViewBackground.image = UIImage(named: "YOUR IMAGE NAME GOES HERE")
    
        // you can change the content mode:
        imageViewBackground.contentMode = UIViewContentMode.scaleAspectFill
    
        self.view.addSubview(imageViewBackground)
        self.view.sendSubview(toBack: imageViewBackground)
    }
    
    0 讨论(0)
  • 2020-11-27 05:10

    Note That:

    I posted this answer from my old account (which is deprecated for me and I can't access it anymore), this is my improved answer.


    You can do it programmatically instead of creating an IBOutlet in each view. just create a UIView extension (File -> New -> File -> Swift File -> name it whatever you want) and add:

    extension UIView {
    func addBackground() {
        // screen width and height:
        let width = UIScreen.mainScreen().bounds.size.width
        let height = UIScreen.mainScreen().bounds.size.height
    
        let imageViewBackground = UIImageView(frame: CGRectMake(0, 0, width, height))
        imageViewBackground.image = UIImage(named: "YOUR IMAGE NAME GOES HERE")
    
        // you can change the content mode:
        imageViewBackground.contentMode = UIViewContentMode.ScaleAspectFill
    
        self.addSubview(imageViewBackground)
        self.sendSubviewToBack(imageViewBackground)
    }}
    

    Now, you can use this method with your views, for example:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        self.view.addBackground()
    }
    
    0 讨论(0)
  • 2020-11-27 05:16

    `

    CGRect screenRect = [[UIScreen mainScreen] bounds];
    
    CGFloat screenWidth = screenRect.size.width;
    
    CGFloat screenHeight = screenRect.size.height;
    
    _imgBackGround.frame = CGRectMake(0, 0, screenWidth, screenHeight);` 
    
    0 讨论(0)
提交回复
热议问题