簡體   English   中英

如何以編程方式調整 UIButton 內的圖像大小?

[英]How to resize an image inside an UIButton programmatically?

我有這個 UIButton 和一個適合的圖像。我不希望圖像占據按鈕內的所有空間,而只是在中心的一小部分,但是如果我調整按鈕的大小,它也會調整圖像的大小. 我該怎么做,有沒有一個選項可以獨立於 UIButton 的大小來設置我想要的任何尺寸? 謝謝!

這可以通過以下方式通過代碼完成:

    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)

這樣,您就可以實現您想要的。

您可以嘗試使用圖像視圖插圖。 每個 UIButton 都有一個屬性 imageView。

在 Swift 3 中,你可以這樣做:

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

紅色背景只是讓你知道發生了什么變化

在我使用 contentHorizo​​ntalAlignment 和 contentVerticalAlignment 都設置為 .fill 之前,我無法讓按鈕的 imageView 調整大小。 然后使用 imageEdgeInsets 我重新定位圖像。

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)

結果:

在此處輸入圖片說明

我會這樣做:

UIButton只是一個UIView 您可以簡單地添加帶有設置圖像的UIImageView並在UIButton上調用addSubview

考慮到 KVISH 在我實施之前所說的話,它按預期工作。 我發布這個是因為侯曼要求舉個例子。

//grab the image using the name of the pic
var image = UIImage(named: "picture")

//set the size for the image
image = image?.resize(toWidth: 18)
image = image?.resize(toHeight: 18)

//set the image to the button
buttonName.setImage(image, for: UIControlState.normal)

//adjust the position
buttonName.imageEdgeInsets = UIEdgeInsetsMake(8,16,9,0)

這些可以通過將 imageEdgeInsets 添加到 UIButton 來實現。

在 swift4.2

  button.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

從 iOS 13 開始,當使用 SF Symbols 時,我更喜歡這個:

let button = UIButton()
let font = UIFont.systemFont(ofSize: 30) // <- make it larger, smaller, whatever you want. 
let config = UIImage.SymbolConfiguration(font: font)
let image = UIImage(systemName: "bag.badge.plus", withConfiguration: config)
button.setImage(image, for: .normal)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM