7

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

J. Chomel
  • 8,193
  • 15
  • 41
  • 69
anusha hrithi
  • 709
  • 2
  • 9
  • 13

3 Answers3

24

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)
Gaurav Saini
  • 177
  • 1
  • 1
  • 8
drv
  • 788
  • 9
  • 16
  • @drdrdrdr Could you please check my question http://stackoverflow.com/questions/43995059/how-to-add-images-for-different-screen-size-from-assets-xcassets-in-xcode-8 ? – May Phyu May 16 '17 at 07:46
8

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)
Arafin Russell
  • 1,487
  • 1
  • 18
  • 37
1

Update for swift3 :

    UIGraphicsBeginImageContext(self.frame.size)

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

    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!

    UIGraphicsEndImageContext()

    backgroundColor = UIColor(patternImage: image)
Fares Benhamouda
  • 589
  • 8
  • 21