I'm trying to place an UIImageView
in the parent view's center. Image must keep its original aspect ratio and also it shouldn't exceed parent's bounds. So landscape images should be limited by parent's width and portrait images should occupy as much vertical space as needed keeping original ratio.
Sounds like quite a simple task for AutoLayout, right? Here's my setup for UIImageView
:
- center vertically in parent
- center horizontally in parent
- imageView.width <= superview.width
- imageView.height <= superview.height
I also set contentMode
to Aspect Fit
. Everything works really great for small images which are smaller than device screen but for some reason my UIImageView
takes more space than its underlying UIImage
for large images (notice the green background - imageView.backgroundColor = [UIColor greenColor]
).
Why is this happening? I am not an AutoLayout expert by my constraints look reasonable to me. If I use smaller images like 200x400 then UIImageView
takes exactly 200x400 points on the screen with no extra green areas.
I'd like to add borders and rounded corners which obviously won't work properly in this case.