11

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?

axl411
  • 920
  • 1
  • 7
  • 23

2 Answers2

29

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

Community
  • 1
  • 1
benhameen
  • 1,418
  • 15
  • 24
  • Didn't worked for me. In Ipad IOS 10 I am trying to set image on UIbutton. Button size 150x150 and image is bigger than that. When I try to set image on it, It takes top left corner of that image – Darshan Mothreja Feb 09 '17 at 09:55
  • @DarshanMothreja this question specifically addresses images that are smaller than the UIButton; you are asking about when the image is bigger than the UIButton. You're welcome to open up a new question and I can see if I can help you with your specific situation. I'd have to see some of the code you're using to set the image of the UIButton in order to make the best judgement. – benhameen Feb 09 '17 at 17:48
1

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

- (void)layoutSubviews {
    [super layoutSubviews];
    self.imageView.frame = self.bounds;
}
Kevin
  • 51
  • 1