【发布时间】:2018-11-20 04:56:37
【问题描述】:
我想增加一个图片按钮的触控区域,在搜索过程中,我发现了一种使用CALayer 的contentsCenter 属性的方法。
https://developer.apple.com/documentation/quartzcore/calayer/1410740-contentscenter
上面的文档示例显示了一个位于图层中心的图像,可以随着图层大小的变化而调整大小,同时保持contentsCenter 属性中定义的比例。
但是当我使用contentsCenter 属性时,它只会拉伸图像的中心 - (0.5, 0.5)。
所以我将contentsGravity 属性添加到.center,但导致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
如何让图片居中在一个按钮内并保持插图的比例?
【问题讨论】:
-
嗯,问题的整个前提是错误的。
contentsCenter属性与如何“增加图像按钮的触摸区域”无关。所以这就是我们所说的 x-y 问题:你假设你的真正问题有一个错误的解决方案,现在你在问为什么这个错误的解决方案是错误的,而不是问真正的问题。我建议您放弃这个问题,而是询问如何“增加图像按钮的触摸区域”。