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

for*_*yez 14 uibutton 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)
Run Code Online (Sandbox Code Playgroud)

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

Leo*_*bus 22

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")
}
Run Code Online (Sandbox Code Playgroud)
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)
}
Run Code Online (Sandbox Code Playgroud)

  • iOS 15 中已弃用“UIButton.imageEdgeInsets” (2认同)

Roh*_*hth 10

在不必处理内容插入的情况下,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
Run Code Online (Sandbox Code Playgroud)


Sha*_*med 7

迅捷5,迅捷4,迅捷3

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

要么

btnetc.imageView?.contentMode = .scaleAspectFit
Run Code Online (Sandbox Code Playgroud)

要么

btnetc.imageView?.contentMode = .scaleToFill
Run Code Online (Sandbox Code Playgroud)

  • 按钮应为 100x100,图像应为 50x50,我不明白您的解决方案如何处理这个问题? (2认同)

Mic*_*ael 6

XIB选择你的后UIButton.

只要确保你的插图都是一样的.


在此输入图像描述