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];
The easiest way to programmatically set a UIButton imageView in aspect fit mode :
Swift
Objective-C
Note: You can change .scaleAspectFit (UIViewContentModeScaleAspectFit) to .scaleAspectFill (UIViewContentModeScaleAspectFill) to set an aspect fill mode
Background image can actually be set to scale aspect fill pretty easily. Just need to do something like this in a subclass of UIButton:
1 - clear Button default text (important)
2 - set alignment like image
3 - set content mode like image
You just need to set content mode of UIButton imageview for three events. -
We have code for three event bcoz while highlighting or selecting if button size is SQUARE and image size is rectangle then it will show square image at the time of highlighting or selecting.
I am sure it will work for you.
This can now be done through IB's UIButton properties. The key is to set your image as a the background, otherwise it won't work.
Swift 5.0