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?
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
Try this:
1. inherit from UIButton
2. override layoutSubviews method, like this:
- (void)layoutSubviews {
[super layoutSubviews];
self.imageView.frame = self.bounds;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With