如何缩放图像并将其置于Swift中的UIButton上?

时间:2014-12-26 05:42:11

标签: swift uibutton

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)

我有一个我已经在我的按钮上设置的图像,但我想将它缩放到比按钮小(例如图像应该是50,50)并且按钮的中心。我怎么能在Swift中做到这一点?

4 个答案:

答案 0 :(得分:21)

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)
}

答案 1 :(得分:8)

在您不必处理内容插入的情况下,Ther是一种更简单的方法。这是:

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

答案 2 :(得分:7)

选择XIB后通过UIButton

只需确保您的插图完全相同。

enter image description here

答案 3 :(得分:6)

Swift 5,Swift 4,Swift 3

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

btnetc.imageView?.contentMode = .scaleAspectFit

btnetc.imageView?.contentMode = .scaleToFill