jazzedge
11/25/2017 - 4:51 PM

Swift - Gradient and Background with Re-Orientation

  1. Create a PNG image 2732 x 2732.
  2. Using GIMP, create a portrait version by changing the size of the image to w2048 x h2732
  3. Repeat to create a landscape version of w2732 x h2048
  4. Name the 2 image files differently
  5. Drag them into the Xcode assets file. Use the same image for all three resolutions x1, x2, x3
  6. Create a function in your view controller to setBackgroundImage
  7. Call the function from viewDidLoad
  8. Use either (a) viewWillTransition or (b) viewDidLayoutSubviews to call setBackgroundImage
  9. Note that you must set Xcode target General>Deployment Info>Device Orientation. Also note Upside Down doesn't work.
Source: SVG-Test

See: https://dzone.com/articles/calayer-and-auto-layout-with-swift-1

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var imgBackground: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setBackgroundImage()
        view.layer.addSublayer(gradientLayer)
        gradientLayer.frame = view.bounds

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

//    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
//        super.viewWillTransition(to: size, with: coordinator)
//        print ("Orientation changed")
//        setBackgroundImage()
//        self.imgBackground.layer.frame = self.view.bounds
//    }
    

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        print ("Orientation changed")
        setBackgroundImage()
        gradientLayer.frame = view.bounds
    }
    
    func setBackgroundImage() {
        print ("setBackgroundImage")
        let orientation = UIDevice.current.orientation
        if orientation.isLandscape {
            imgBackground.image = UIImage(named: "orange-apple-2732x2732l.png")
            print ("Landscape")
        } else {
            imgBackground.image = UIImage(named: "orange-apple-2732x2732p.png")
            print("Portrait")
        }
    }

    let gradientLayer: CAGradientLayer = {
        let layer = CAGradientLayer()
        layer.colors = [
            UIColor.clear.cgColor,
            UIColor.blue.cgColor
        ]
        return layer
    }()
    
}