Search code examples
iosxcodeuistoryboardnslayoutconstraintaspect-ratio

Image View 16:9 aspect ratio


I want all of my images in a specific Image View to fit in a 16:9 aspect ratio. The image should resize to fit itself into those contraints without changing its own aspect ratio.

So for example, if I have an image with an aspect ratio of 4:3, it should resize itself, while keeping its aspect ratio, to the Image View's contraints of 16:9.

So my question is, using the interface builder, how do I set an Image View to have a 16:9 aspect ratio?


Solution

  • Steps:

    1. Add a Width constraint and an Aspect Ratio constraint like below: (NOTE: You can also do with leading, trailing constraints -- they resolve the X position. For solving the Y position, you can add either top or bottom constraint (OR) an Align Center Y constraint.):

    Constraints

    1. Select your image view and go to the Size Inspector, select edit for the aspect ratio constraint you just added, and input 16:9 to the multiplier there. Aaannddd you are done.

    If you change the width constraint, the height will automatically change respecting the aspect ratio. Make sure you set your ImageView's content mode to be scaleAspectFill.

    Edit Aspect Ratio