0

I am prototyping a simple single page ios app. I am trying to get the background to swap between two images when the device orientation switches from portrait to landscape. '''

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {

    UIGraphicsBeginImageContext(self.view.frame.size)

    switch UIDevice.current.orientation{
    case .portrait:
        UIImage(named: "img_001")?.draw(in: self.view.bounds)
    case .portraitUpsideDown:
        UIImage(named: "img_001")?.draw(in: self.view.bounds)
    case .landscapeLeft:
        UIImage(named: "img_002")?.draw(in: self.view.bounds)
    case .landscapeRight:
        UIImage(named: "img_002")?.draw(in: self.view.bounds)
    default:
        break
    }

    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    self.view.backgroundColor = UIColor(patternImage: image)

}

'''

The background changes when the device flips but the image is tiled on the display whereas it needs to be a single image that fills the screen.

  • Use an `UIImageView` instead of setting `backgroundColor`. This way you don't need to think about resizing the image to fit the screen. Just use `contentMode = .aspectFill`. – Sweeper Sep 17 '19 at 05:51

1 Answers1

1

Slightly updated your code to use correct "size" and "bounds"

UIGraphicsBeginImageContext(size)
    var bounds = self.view.bounds
    bounds.size = size

    switch UIDevice.current.orientation{
    case .portrait:
        UIImage(named: "download.jpg")?.draw(in: bounds)
    case .portraitUpsideDown:
        UIImage(named: "download.jpg")?.draw(in: bounds)
    case .landscapeLeft:
        UIImage(named: "download.jpg")?.draw(in: bounds)
    case .landscapeRight:
        UIImage(named: "download.jpg")?.draw(in: bounds)
    default:
        break
    }

    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    self.view.backgroundColor = UIColor(patternImage: image)

You can get more help from here

Sunil Bhosale
  • 146
  • 1
  • 6