繁体   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