ios - CALayer 的内容中心无法快速工作

标签 ios swift image calayer

我想增加图像按钮的触摸区域,当我搜索时,我找到了一种使用 CALayercontentsCenter 属性的方法。

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/

相关文章:

image - OpenCL - 传递 image2d_t 两次以从内核读取和写入?

CSS Nav Menu Text 罕见的大小对齐底部的行为

iphone - 如何在iOS/iPhone/iPad上以编程方式了解多少电池电量?

ios - Swift 3 转换 "has no member"错误

ios - 如何让两个 UIButton 像 Swift 中的单选按钮一样执行?

swift - 找不到接受类型参数列表的 XCTAssertEqual 的重载 ([String : AnyObject], [String : AnyObject])

swift - 从 OS X 上的 xcassets 加载应用程序图标

ios - PFQueryTableViewController,用于查询的异步和同步加载 Parse swift

javascript - 缩小图像和 div 高度的问题 - CSS/

ios - UICollectionViewCellawakeFromNib 从未被调用,即使 registerNib 被调用