I want to add an image to a UIButton, and also want to scale my image to fit with the UIButton (make image smaller). Please show me how to do it.
This is what I have tried, but it does't work:
- Adding image to button and using
setContentMode
:
[self.itemImageButton setImage:stretchImage forState:UIControlStateNormal];
[self.itemImageButton setContentMode:UIViewContentModeScaleAspectFit];
- Making a "stretch image":
UIImage *stretchImage = [updatedItem.thumbnail stretchableImageWithLeftCapWidth:0 topCapHeight:0];
If you really want to scale an image, do it, but you should resize it before using it. Resizing it at run time will just lose CPU cycles.
This is the category I'm using to scale an image :
UIImage+Extra.h
UIImage+Extra.m
You can use it to the size you want. Like :
Expanding on Dave's answer, you can set the
contentMode
of the button'simageView
all in IB, without any code, using Runtime Attributes:1
meansUIViewContentModeScaleAspectFit
,2
would meanUIViewContentModeScaleAspectFill
.I had problems with the image not resizing proportionately so the way I fixed it was using edge insets.
The cleanest solution is to use Auto Layout. I lowered Content Compression Resistance Priority of my
UIButton
and set the image (not Background Image) via Interface Builder. After that I added a couple of constraints that define size of my button (quite complex in my case) and it worked like a charm.make sure that you have set the image to Image property, but not to the Background
I had the same problem. Just set the ContentMode of the ImageView that is inside the UIButton.
Hope this helps.