Skip to content

Instantly share code, notes, and snippets.

@manmal
Created May 12, 2021 08:07
Show Gist options
  • Select an option

  • Save manmal/97247dcea0bdcee92d935d926037ecac to your computer and use it in GitHub Desktop.

Select an option

Save manmal/97247dcea0bdcee92d935d926037ecac to your computer and use it in GitHub Desktop.
UIImage+LaunchImage
import UIKit
extension UIImage {
/// Available launch images (as of 12 May 2021):
/// LaunchImage-800-667h@2x.png: 750x1334
/// LaunchImage-1200-Portrait-1792h@2x.png: 828x1792
/// LaunchImage-800-Portrait-736h@3x.png: 1242x2208
/// LaunchImage-1100-Portrait-2436h@3x.png: 1125x2436
/// LaunchImage-1200-Portrait-2688h@3x.png: 1242x2688
static var launchImage: UIImage {
let images: [(height: CGFloat, name: String)] = [
(1334, "LaunchImage-800-667h@2x.png"),
(1792, "LaunchImage-1200-Portrait-1792h@2x.png"),
(2208, "LaunchImage-800-Portrait-736h@3x.png"),
(2436, "LaunchImage-1100-Portrait-2436h@3x.png")
]
let image = images
.first { $0.height <= UIScreen.main.nativeBounds.height }
.map(\.name)
.map(UIImage.init(named:))
return (image ?? UIImage(named: "LaunchImage-1200-Portrait-2688h@3x.png"))!
}
}
@marcpalmer
Copy link
Copy Markdown

marcpalmer commented May 12, 2021

Here's a further suggestion, not sure if it's better:

extension UIImage {
    /// Available launch images (as of 12 May 2021):
    /// LaunchImage-800-667h@2x.png: 750x1334
    /// LaunchImage-1200-Portrait-1792h@2x.png: 828x1792
    /// LaunchImage-800-Portrait-736h@3x.png: 1242x2208
    /// LaunchImage-1100-Portrait-2436h@3x.png: 1125x2436
    /// LaunchImage-1200-Portrait-2688h@3x.png: 1242x2688
    static var launchImage: UIImage {
        let images: [(height: CGFloat, name: String)] = [
            (1334, "LaunchImage-800-667h@2x.png"),
            (1792, "LaunchImage-1200-Portrait-1792h@2x.png"),
            (2208, "LaunchImage-800-Portrait-736h@3x.png"),
            (2436, "LaunchImage-1100-Portrait-2436h@3x.png"),
            (.greatestFiniteMagnitude, "LaunchImage-1200-Portrait-2688h@3x.png") // The default if none match
        ]
        let image = images
            .first(where: { $0.height <= UIScreen.main.nativeBounds.height })
            .map(\.name)
            .flatMap(UIImage.init(named:))
        return image!
    }
}

The flatMap is required because the name is Optional, and then can be mapped to an UIImage?? and the flatMap can flatten that to a single level of optionality (I had to look that up)

@marcpalmer
Copy link
Copy Markdown

Changing .first(where: { $0.height <= UIScreen.main.nativeBounds.height }) to .first(where: { $0.height >= UIScreen.main.nativeBounds.height }) should get you the correct logic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment