-1

I have a UIImageView with an image attached to it. I'd like to display it centered both vertically and horizontally in a way that looks the same on all iPhones, no matter if it's iPhone 5 or 6S Plus.

By 'look the same', I mean the UIImageView should take 80% of screen width and height. Is it possible to achieve that using constraints only (no code)?

With size classes enabled, the canvas size is a fixed 600 by 600 points. What if I set a constraint that says (make sure the top of my image view is located 20 points from the upper margin). How does it translate to real pixels on the device? I've heard that on non-retina display it is 20 pixels, on newer its 40 and 60 respectively (2x, and 3x on 6S).

So is it true that ideally, I shouldn't actually specify the constraints with specific values (in points), but rather use fractions, right? 20 points on iPhone 5 is a different fraction of screen width than on for instance iPhone 6S Plus.

user5539357
  • 1,024
  • 1
  • 9
  • 19
  • Possible duplicate of [How to create percentage of total width using autolayout?](http://stackoverflow.com/questions/26373598/how-to-create-percentage-of-total-width-using-autolayout) – juanjo Jan 10 '16 at 22:34

1 Answers1

0

Just translate what you wrote into constraints:

I'd like to display it centered both vertically and horizontally

Constrain the image view's CenterX and CenterY attributes to be equal to the superview's CenterX and CenterY attributes, respectively.

the UIImageView should take 80% of screen width and height

Constrain the image view's height to be equal to the superview's height with a multiplier of 0.8. Similarly for the width.

Now, you should realize that 80% of the size of the screen will not always have the same aspect ratio. So, whether that satisfies as "a way that looks the same on all iPhones" is up to you.

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154
  • I should have said 80% of the screen width, right. But is it actually possible to adjust the height of UIImageView based on image to be displayed so that the aspect ratio of that image is preserved? Without a line of code maybe? – user5539357 Jan 10 '16 at 22:40
  • Setting the image view's `contentMode` to `UIViewContentModeScaleAspectFit` should do it. – Ken Thomases Jan 10 '16 at 22:48
  • It scales the content of image, not the image view itself. – user5539357 Jan 11 '16 at 09:32
  • Why is that not good enough? Anyway, the image view should size itself to its content via the intrinsic size mechanism, if other constraints allow it. However, since you're forcing the width, it won't automatically maintain its aspect ratio. If the image is fixed, you can set up an aspect ratio constraint for it. That plus the width constraint will do what you need. If the image may change, you would have to do that programmatically each time you change it. – Ken Thomases Jan 11 '16 at 16:29