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 screen. My code looks like this: self.view.backgroundColor = UIColor(patternImage: UIImage(named: "backgroundImage")!)
Does anyone know how to make the background an image that will take up the whole screen, and would scale when appearing on different iPhone screen sizes?
Image resize function in swift as below. func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage { let size = image. size let widthRatio = targetSize. width / size.
To make an image scales to fit the current view, we use the resizable() modifier, which resizes an image to fit available space. We can see the whole image now, but it got stretched out and losing its aspect ratio, which is usually not the behavior we want. The image view resize to fit available space.
Go to 'View->Show Library' and choose the Image View and drag it to the middle of the screen until it snaps perfectly in the center. This Image View will serve as the background image and it will fill the entire screen, including the area past the safe area view.
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() }
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