Search code examples
arraysswiftbackgroundbackground-image

I change my BackgroundImage with a randomElement from an Array but its zoomed in and not fitting perfectly


I have an array with my Image-names and a button. When I click on the button, the background-image schould get chaged. All is working but the pictures are a little bit zoomed and are not scaled to screen size.

import UIKit

class ViewController: UIViewController {


    override func viewDidLoad() {
        super.viewDidLoad()
    }

    var imagesArray = ["1", "2", "3", "4"]



    @IBAction func changeBackgroundImageButton_Tapped(_ sender: UIButton) {

        if let randomImage = imagesArray.randomElement(){

            view.backgroundColor = UIColor(patternImage: UIImage(named: randomImage)!)
        }

    }

}

So what should I do that the background-images are not zoomed and scaled perfectly? Thanks!


Solution

  • To change background image of your view randomly, there is minor changes - that will update your background image and also it will not hide your button.

    
    @IBAction func changeBackground_Tapped(_ sender: Any) {
    
            UIGraphicsBeginImageContext(view.frame.size)
            UIImage(named: imagesArray.randomElement() ?? "1")?.draw(in: view.bounds)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
    
            if let image = image {
                view.backgroundColor = UIColor(patternImage: image)
            }
    
    }
    
    

    Hope it will solve your issue.