Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set background image in swift?

Tags:

ios

swift

uiimage

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 “!”)

like image 239
anusha hrithi Avatar asked Jul 28 '16 06:07

anusha hrithi


People also ask

How do I change the background in SwiftUI?

The first way would be to use the . background modifier and pass Color which is a view in SwiftUI. The second approach would be using ZStack and add one color or multiple colors wrapped in VStack for vertical and HStack for horizontal layout.

How do I add an Image to SwiftUI?

To display an image, simply add the image file into your asset library (Assets. xcassets) and then pass the name of the asset as a string to your Image element in Line 1.

How do I crop an Image in SwiftUI?

To use the Image extension , just put it in a file in your project (a name like image-centercropped. swift will work nicely). Then just add . centerCropped() to any image you want to be center cropped.


3 Answers

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)
like image 90
drv Avatar answered Oct 07 '22 12:10

drv


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)
like image 34
Arafin Russell Avatar answered Oct 07 '22 12:10

Arafin Russell


Update for swift3 :

    UIGraphicsBeginImageContext(self.frame.size)

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

    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!

    UIGraphicsEndImageContext()

    backgroundColor = UIColor(patternImage: image)
like image 42
Fares Benhamouda Avatar answered Oct 07 '22 12:10

Fares Benhamouda