axl411 axl411 - 1 month ago 10x
iOS Question

Setting ContentMode to AspectFill on ImageView of UIButton not work with smaller images

I have a

that downloads its image from the network, I want the content mode to be "aspect fill", so I did this:

btn.imageView.contentMode = UIViewContentModeScaleAspectFill;

then I simply call:

[btn setImage:image forState:UIControlStateNormal];

And this works for images those are larger than the button. They are scaled to fit in the button with aspect ratio unchanged. But for images those are smaller than the button, they are simply displayed at the center without being stretched.

To fix this I tried making an resizable image with the image I retrieved, then call
on my button, but this didn't work.

So I end up having to manually draw a resized image for each image that is smaller than my button then using the drawn image for my button, but I don't like this solution.

So my question is how can I get smaller images scaled properly on my button without having to manually draw a resized image for that every time?


I have had this same issue. Try this:

    [btn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentFill];
    [btn setContentVerticalAlignment:UIControlContentVerticalAlignmentFill];

From my understanding, when setting the image, the button's UIImageView's size/frame is set to that of the image, so when it is smaller, it isn't constrained by the UIButton's frame, and thus sits happily, unchanged, in the middle of the button.

To fix this, we need to force the UIImageView to take up the full size of the UIButton, and setting its alignment takes care of this.

See for more info (though it refers to this as an AutoLayout issue):