Shai UI
Shai UI

Reputation: 51978

How to scale image and center it on a UIButton in Swift?

var button = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
var image = UIImage(named: "myimage.png") as UIImage!
button.frame = CGRectMake(0, 0, 100, 100)
button.setImage(image, forState: .Normal)

I have an image that I've set on my button, but I'd like to scale it to be smaller than the button (for example the image should be 50,50) and center in the button. How might I do this in Swift?

Upvotes: 19

Views: 45021

Answers (5)

Dee Dan
Dee Dan

Reputation: 1

Xcode 13, Swift 5

Using storyboard, select the button, then in the size inspect click the dropdown on size just above Content inset. There is a list of sizes to select from, and this will adjust your image size(if you use system image). The default size is already set when you added the button on the storyboard to the View Controller.

Upvotes: 0

Shakeel Ahmed
Shakeel Ahmed

Reputation: 6041

Swift 5, Swift 4, Swift 3

var image = UIImage(named: "myimage") as UIImage!   
btnetc.setImage(image, for: .normal)
btnetc.imageView?.contentMode = .scaleAspectFill

or

btnetc.imageView?.contentMode = .scaleAspectFit

or

btnetc.imageView?.contentMode = .scaleToFill

Upvotes: 12

Leo Dabus
Leo Dabus

Reputation: 236538

Xcode 8.3.1 • Swift 3.1

let button = UIButton(type: .custom)
let image = UIImage(named: "myimage.png")

func buttonTouchDown(_ button: UIButton) {
    print("button Touch Down")
}

override func viewDidLoad() {
    super.viewDidLoad()
    button.frame = CGRect(x: 0, y: 0 , width: 100, height: 100)
    button.backgroundColor = .clear
    button.addTarget(self, action: #selector(buttonTouchDown), for: .touchDown)
    button.setTitle("Title", for: .normal)
    button.setTitleColor(.black, for: .normal)
    button.setImage(image, for: .normal)
    button.imageEdgeInsets = UIEdgeInsetsMake(25,25,25,25)
    view.addSubview(button)
}

Upvotes: 26

Rohan Vasishth
Rohan Vasishth

Reputation: 241

Ther is a much easier way to do this where you don't have to deal with content insets. Here its is:

var button = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
var image = UIImage(named: "myimage.png") as UIImage!
button.frame = CGRectMake(0, 0, 100, 100)
button.setImage(image, forState: .Normal)
button.contentMode = .center
button.imageView?.contentMode = .scaleAspectFit

Upvotes: 10

Michael
Michael

Reputation: 9904

Or via XIB after selecting your UIButton.

Just make sure your insets are all the same.


enter image description here

Upvotes: 7

Related Questions