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 “!”)
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With