Search code examples
iosxcodeiphone-xxcasset

How can I add a fullscreen image for iPhone X to xcassets (not a launch image)?


I have a background image in my landscape app which covers the entire screen. I have added it to xcassets using @1x, @2x and @3x as usual.

On all devices, except for the iPhone X, the image displays correctly. However, because the iPhone X has a different aspect ratio than other iPhones, it is cropped at the sides. If I choose Aspect Fill, it is stretched and looks poor.

I have created an additional background image in the correct aspect ratio of the iPhone X, but how do I add it to xcassets? There are only options for @1x, @2x and @3x. Am I missing something?

(I must stress this is NOT a launch image - it's an image in an image view which serves as the background to all the screens on my app).

EDIT

For anyone else struggling with this, this was how I did it thanks to the4kman's help:

override func viewDidLayoutSubviews() {
    // Work out aspect ratio to show correct background image
    let imageWidth = background.bounds.width
    let imageHeight = background.bounds.height
    let aspectRatio = imageWidth / imageHeight

    if aspectRatio >= 2.0 {  // iPhone X ratio is 2.16, other iPhones are 1.77
        background.image = UIImage(named: "background-X")
    } else {
        background.image = UIImage(named: "background")
    }
}

Solution

  • You cannot have images with different aspect ratios in one image asset. You should add a different asset if you want to target the iPhone X specifically. Give it a suffix to distinguish it from the original image (for e.g. "-x").