设置图像在背景中心与内部空间围绕一个按钮

时间:2018-01-27 06:21:03

标签: ios swift uibutton uiimage

我已将背景图像设置为按钮,并已将layer.cornerRadius应用于该按钮,以便按钮就像一个圆圈,但是图像是从角落切割的,所以如何将图像放在中心一个按钮,以便当我应用layer.cornerRadius时不应该从角落切割图像,是否有办法让我可以从内侧到按钮框架创建一个空间。

以下是我的尝试:

myCheckBoxButton.setBackgroundImage(#imageLiteral(resourceName: "check-square"), for: .normal)
myCheckBoxButton.frame = CGRect(x: 120, y: 10, width: 40, height: 40)
myCheckBoxButton.backgroundColor = .blue
myCheckBoxButton.layer.cornerRadius = 20
myCheckBoxButton.showsTouchWhenHighlighted = true
myCheckName.text = "Checkbox"
myCheckName.textColor = .gray
myCheckName.frame = CGRect(x: 100 , y: 60, width: 80, height: 15)

enter image description here

在aleksmutlu的回答之后更新

一切都是正确的,但图像不是白色透明的,似乎是蓝色的

enter image description here

更新完成

将按钮类型添加为自定义

let myCheckBoxButton = UIButton(type: .custom)

1 个答案:

答案 0 :(得分:0)

您可以将图像设置为按钮的内容,并为其添加一些插图,而不是设置背景图像。

myCheckBoxButton.setImage(#imageLiteral(resourceName: "check-square"), for: .normal)
myCheckBoxButton.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10)