使用 AutoLayout 用 UILabel 屏蔽 UIView

Masking A UIView With UILabel Using AutoLayout

我正在从事一个可以达到预期效果的项目:

我使用以下代码成功绘制了我的圆圈:

let circle = CircleView()
circle.translatesAutoresizingMaskIntoConstraints = false
circle.backgroundColor = UIColor.clear
self.addSubview(circle)

    // Setup constraints
    circle.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
    circle.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
    circle.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.6).isActive = true
    circle.heightAnchor.constraint(equalTo: circle.widthAnchor, multiplier: 1.0/1.0).isActive = true

作为参考,这是我的 CircleView class:

class CircleView: UIView {

    override func draw(_ rect: CGRect) {

        // Set the path
        let path = UIBezierPath(ovalIn: rect)

        // Set the fill color
        UIColor.black.setFill()

        // Fill
        path.fill()
    }
}

随后,我将创建我的 UILabel,如下所示:

let myLabel = UILabel()
myLabel.translatesAutoresizingMaskIntoConstraints = false
myLabel.text = "HELLO"
myLabel.textColor = UIColor.white
circle.addSubview(myLabel)

    // Setup constraints
    myLabel.centerXAnchor.constraint(equalTo: circle.centerXAnchor).isActive = true
    myLabel.centerYAnchor.constraint(equalTo: circle.centerYAnchor).isActive = true

我试图通过以下方式掩盖我的圈子:

circle.mask = myLabel

然而,这会导致我所追求的相反效果(我的文本不是 UIView 中的剪切,而是我的文本现在是黑色的)。实现这种效果我可能哪里出错了?

遮罩以相反的方式工作,当遮罩上的颜色不透明时,它将显示该像素位置的内容,当像素透明时,它将隐藏内容。

由于使用 UILabel 无法实现此目的,因此您需要使用其他东西作为掩码,例如 CALayer.

如果您查找 "UILabel see through text",您应该会找到类似于 this 的结果,这基本上也适用于您(有一些变化)。

实例化您的 CircleView,然后实例化一个 CATextLayer 并将其用作您的 UIView

的掩码