Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

uibutton

I have a UIButton 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 setImage:forState: 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?

like image 675
axl411 Avatar asked Dec 02 '14 10:12

axl411


2 Answers

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): https://stackoverflow.com/a/28205566/3692828

like image 179
benhameen Avatar answered Oct 05 '22 10:10

benhameen


Try this:
1. inherit from UIButton
2. override layoutSubviews method, like this:

- (void)layoutSubviews {
    [super layoutSubviews];
    self.imageView.frame = self.bounds;
}
like image 45
Kevin Avatar answered Oct 05 '22 11:10

Kevin