How to resize an image inside an UIButton programmatically?

This can be done through code in the following way:

    let imageSize:CGSize = CGSize(width: 20, height: 20)

    let button:UIButton = UIButton(type: UIButton.ButtonType.custom)
    button.frame = CGRect(x: 200, y: 200, width: 60, height: 60)
    button.backgroundColor = UIColor.yellow
    button.setImage(UIImage(named: "chat.png"), for: UIControl.State.normal)

    // The below line will give you what you want
    button.imageEdgeInsets = UIEdgeInsets(
        top: (button.frame.size.height - imageSize.height) / 2,
        left: (button.frame.size.width - imageSize.width) / 2,
        bottom: (button.frame.size.height - imageSize.height) / 2,
        right: (button.frame.size.width - imageSize.width) / 2)

    self.view.addSubview(button)

This way, you can achieve what you wanted.


I would do it this way:

A UIButton is just a UIView. You can simply add a UIImageView with a set image and call addSubview on the UIButton.


I couldn't get the button's imageView to resize until I used contentHorizontalAlignment and contentVerticalAlignment both set to .fill. Then using imageEdgeInsets I repositioned the image.

let button = UIButton()
let image = UIImage(systemName: "bag.badge.plus")
button.setImage(image, for: .normal)
button.contentHorizontalAlignment = .fill
button.contentVerticalAlignment = .fill
button.imageEdgeInsets = UIEdgeInsets(top: 6, left: 6, bottom: 10, right: 10)

Result:

enter image description here


You can experiment with image view insets. Every UIButton has a property imageView.

In Swift 3 you can do this like so:

//let button = UIButton()
button.imageView?.backgroundColor = UIColor.red
button.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10)

red background is just so you know what is changing