Search code examples
iosswiftuiviewnslayoutconstraint

Aspect ratio issues with Iphone X


I developed most of my UI on storyboard by creating constraint setup with aspect ratio. Now I find out that on iphone X all the constraint with ratio looks stretched and incorrect. What is the best solution to set constraint with aspect ratio that best fit across all iphone sizes?


Solution

  • You are confusing "aspect ratio" with "percentage".

    If you want your background image to not look "stretched" when the size changes, you need to either give it an aspect ratio + percentage size, or use different images.

    For example:

    • an iPhone SE screen is 320 x 568 so an image that is 50% of the height (and 100% of the width) will be 320 x 284.

    • an iPhone 8 screen is 375 x 667 so an image that is 50% of the height (and 100% of the width) will be 375 x 333.5.

    • an iPhone X screen is 375 x 812 so an image that is 50% of the height (and 100% of the width) will be 375 x 406.

    Obviously, your image cannot be 320 x 284 and 375 x 333.5 and 375 x 406 all at the same time.

    Instead of setting your image view to 50% of the height of the screen, you may need to constrain it to the full width of the screen and give it an Aspect Ratio constraint. It won't cover the same percentage height on each device (don't forget about iPad sizes), but it won't look stretched.