简体   繁体   中英

How to set background image in swift?

I am trying to set aground image to my ViewController in swift language.

I am using the following code :

self.view.backgroundColor = UIColor(patternImage: UIImage(named:”bg.png")!)

But the app is getting crash.It is showing the error like

“fatal error: unexpectedly found nil while unwrapping an Optional value”(Because of the “!”)

That error is thrown because the image "bg.png" does not exist. Usually when you import images to the Assets.xcassets folder, the file extension is removed. So try the following:

self.view.backgroundColor = UIColor(patternImage: UIImage(named:"bg")!)

You will notice that the background will not look as expected, you need to do the following as explained here :

     UIGraphicsBeginImageContext(self.view.frame.size)
    UIImage(named: "bg")?.draw(in: self.view.bounds)
    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    self.view.backgroundColor = UIColor(patternImage: image)

Try this Swift4:

let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
backgroundImage.image = UIImage(named: "bg.png")
backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(backgroundImage, at: 0)

Update for swift3 :

    UIGraphicsBeginImageContext(self.frame.size)

    UIImage(named: "bg").draw(in: self.bounds)

    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!

    UIGraphicsEndImageContext()

    backgroundColor = UIColor(patternImage: image)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM