我有这个 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)
这样,你就可以实现你想要的。
关于ios - 如何以编程方式调整 UIButton 中图像的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40514110/