我想增加图像按钮的触摸区域,当我搜索时,我找到了一种使用 CALayer
的 contentsCenter 属性的方法。
https://developer.apple.com/documentation/quartzcore/calayer/1410740-contentscenter
上面的文档示例显示了一个位于图层中心的图像,该图像可以随着图层大小的变化而调整大小,同时保持 contentsCenter
属性中定义的比例。
但是当我使用 contentsCenter
属性时,它只是拉伸(stretch)图像的中心 - (0.5, 0.5)
。
因此,我向 .center 添加了 contentsGravity
属性,但导致 contentsCenter
属性不起作用。
button.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
button.center = view.center
button.backgroundColor = .clear
let image = UIImage(named: "profileImage")
button.layer.contents = image?.cgImage
button.layer.contentsCenter = CGRect(x: 0.25, y: 0.25, width: 0.5, height: 0.5)
button.layer.contentsGravity = .center
//button.layer.contentsScale = image?.scale
button.layer.borderColor = UIColor.black.cgColor
button.layer.borderWidth = 2
button.layer.cornerRadius = 5
button.layer.masksToBounds = true
如何使图像在按钮内居中并保持比例插入?
最佳答案
您可以使用以下代码增加UIButton
大小
button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
关于ios - CALayer 的内容中心无法快速工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53386472/