Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to adjust an UIButton's imageSize?

How can I adjust the image size of the UIButton? I am setting the image like this:

[myLikesButton setImage:[UIImage imageNamed:@"icon-heart.png"] forState:UIControlStateNormal];

However this fills up the image to the full button, how do I make the image smaller?


Historic note:

For this now 10+ yr old question, you now typically just set the point size using setPreferredSymbolConfiguration

like image 507
adit Avatar asked May 14 '12 01:05

adit


5 Answers

If I understand correctly what you're trying to do, you need to play with the buttons image edge inset. Something like:

myLikesButton.imageEdgeInsets = UIEdgeInsets(top: 30, left: 30, bottom: 30, right: 30)
like image 191
Tim C Avatar answered Nov 16 '22 15:11

Tim C


Tim's answer is correct, however I wanted to add another suggestion, because in my case there was a simpler solution altogether.

I was looking to set the UIButton image insets because I didn't realize that I could set the content mode on the button's UIImageView, which would have prevented the need to use UIEdgeInsets and hard-coded values altogether. Simply access the underlying imageview on the button and set the content mode:

myButton.imageView.contentMode = UIViewContentModeScaleAspectFit;

See UIButton doesn't listen to content mode setting?

Swift 3

myButton.imageView?.contentMode = .scaleAspectFit
like image 39
Kyle Clegg Avatar answered Nov 16 '22 13:11

Kyle Clegg


Swift 3:

button.setImage(UIImage(named: "checkmark_white"), for: .normal)
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
button.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10)
like image 86
Josh O'Connor Avatar answered Nov 16 '22 15:11

Josh O'Connor


Here is the other solution to scale an imageView of UIButton.

button.imageView?.layer.transform = CATransform3DMakeScale(0.8, 0.8, 0.8)
like image 54
ovo Avatar answered Nov 16 '22 14:11

ovo


You can also do that from inteface builder like this.

enter image description here

I think it's helpful.

like image 49
Milos Mandic Avatar answered Nov 16 '22 15:11

Milos Mandic