1

I want to display thumbnails of various size images in a UIImageView. If the image is too big to fit in the UIImageView, I want to only display the amount of the photo that fits in the UIImageView, with the center of the original image in the center of the UIImageView.

I am currently doing this by setting imageView.clipsToBounds = YES; and imageView.contentMode = UIViewContentModeCenter;. This is almost working, except there is a small amount of what appears to be padding inside the layer of the UIImageView. When I try to add a corner radius I can see that the corners are not fully rounded.

When I leave imageView.contentMode as the default value, there is no padding on the sides of the image, but the image is scaled strangely, and not how I want.

Why am I getting this issue with UIViewContentModeCenter, and is there a way to fix it? If not, how can I crop my image on the fly so that I do not have to use UIViewContentModeCenter, but only show the center portion of the image that fits the UIImageView?

Below is how the view looks with imageView.contentMode = UIViewContentModeCenter. See how there is extra padding on the left and right, although when I log the width and x origin of the imageView they appear to be the same as the label above.

With <code>imageView.contentMode = UIViewContentModeCenter. See padding added to sides.</code>

Below is the same exact code as above, but with the default setting for imageView.contentMode. See how there is no padding added, but the image is warped.

Same constraints and UI setup as above, but with default setting for <code>imageView.contentMode</code>

rfj001
  • 7,948
  • 8
  • 30
  • 48

2 Answers2

3

UIViewContentModeCenter keeps the proportions of the imageView, so, when you display it, can show a padding because the image has more height than width, or viceversa.

The default contentMode is UIViewContentModeScaleToFill, so when you use it, the image is expanded in every direction to fill the imageView. That's why you don't see any padding.

If you want to fill the imageView and keep image proportions, then you should use imageView.contentMode = UIViewContentModeScaleAspectFill

Hope it helps

WedgeSparda
  • 1,161
  • 1
  • 15
  • 40
0

I see somethings cut you UIImageView on the left and right side. The width of UIImageView (with UIViewContentModeCenter) is less than normal. I'm not sure about your problem with UIViewContentModeCenter. But there are some ways to work around:

  1. Add UIImageView to UIView, with imageView.contentMode = UIViewContentModeCenter; and cornerRadius UIView.

  2. Use mask for UIImageView: How to Mask an UIImageView

Hope this helps.

Community
  • 1
  • 1
tuledev
  • 10,177
  • 4
  • 29
  • 49