我有这个UIButton和一张图片。我不想让图片占据按钮内的所有空间,而只是在中间的一小部分,但如果我调整按钮的大小,它也会调整图像的大小。我该怎么做呢?有没有一个选项可以独立于UIButton的大小来设置我想要的任何尺寸?谢谢!
发布于 2016-11-10 03:57:57
这可以通过以下方式通过代码完成:
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)这样,你就可以实现你想要的。
https://stackoverflow.com/questions/40514110
复制相似问题