如何以编程方式调整UIButton中的图像大小?

Eli*_*tta 6 xcode ios swift swift3 xcode8

我有这个UIButton和一个适合的图像.我不希望图像占据按钮内的所有空间,但只是它的一小部分位于中心,但如果我调整按钮的大小,它也会调整图像的大小.我怎么能这样做,有没有选择设置我想要的任何尺寸独立于UIButton的大小?谢谢!

Kri*_*aCA 14

这可以通过以下方式通过代码完成:

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

这样,您就可以实现自己想要的目标.


rep*_*guy 9

您可以尝试使用图像视图插图.每个UIButton都有一个属性imageView.

在Swift 3中你可以这样做:

//let button = UIButton()
button.imageView?.backgroundColor = UIColor.red
button.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10)
Run Code Online (Sandbox Code Playgroud)

红色背景只是让你知道什么是变化


Jos*_*llo 9

在我使用 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)
Run Code Online (Sandbox Code Playgroud)

结果:

在此处输入图片说明


KVI*_*ISH 7

我会这样:

A UIButton只是一个UIView。你可以简单地添加UIImageView了一组图像和呼叫addSubviewUIButton

  • 默认情况下,将UIImageView的userInteractionEnabled设置为false (3认同)

Jou*_*e87 6

考虑到 KVISH 在我实施之前所说的,并且它按预期工作。我发布此内容是因为 Houman 要求提供示例。

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


Mur*_*gal 5

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

Run Code Online (Sandbox Code Playgroud)