【问题标题】:CALayer's contentsCenter not working in swiftCALayer 的内容中心无法快速工作
【发布时间】:2018-11-20 04:56:37
【问题描述】:

我想增加一个图片按钮的触控区域,在搜索过程中,我发现了一种使用CALayercontentsCenter 属性的方法。

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 问题:你假设你的真正问题有一个错误的解决方案,现在你在问为什么这个错误的解决方案是错误的,而不是问真正的问题。我建议您放弃这个问题,而是询问如何“增加图像按钮的触摸区域”。

标签: ios swift image calayer


【解决方案1】:

您可以使用以下代码增加UIButton 大小

button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-29
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    相关资源
    最近更新 更多