标签的反向图层蒙版

ale*_*wis 8 uilabel ios

如何反转标签的遮罩层?我有一个textLabel,我用它作为一个imageView包含任意图像的掩码,如下所示:

let image = UIImage(named: "someImage")
let imageView = UIImageView(image: image!)

let textLabel = UILabel()
textLabel.frame = imageView.bounds
textLabel.text = "Some text"

imageView.layer.mask = textLabel.layer
imageView.layer.masksToBounds = true
Run Code Online (Sandbox Code Playgroud)

上述使文本中textLabel具有的字体颜色imageView作为如何通过另一个视图的内容来掩盖视图的层?.

如何扭转这一以去除文本textLabel imageView

rob*_*off 10

创建一个子类UILabel:

class InvertedMaskLabel: UILabel {
    override func drawTextInRect(rect: CGRect) {
        guard let gc = UIGraphicsGetCurrentContext() else { return }
        CGContextSaveGState(gc)
        UIColor.whiteColor().setFill()
        UIRectFill(rect)
        CGContextSetBlendMode(gc, .Clear)
        super.drawTextInRect(rect)
        CGContextRestoreGState(gc)
    }
}
Run Code Online (Sandbox Code Playgroud)

此子类用不透明的颜色填充其边界(在此示例中为白色,但只有alpha通道很重要).然后它使用Clear混合模式绘制文本,混合模式简单地将上下文的所有通道设置为0,包括alpha通道.

游乐场演示:

let root = UIView(frame: CGRectMake(0, 0, 400, 400))
root.backgroundColor = .blueColor()
XCPlaygroundPage.currentPage.liveView = root

let image = UIImage(named: "Kaz-256.jpg")
let imageView = UIImageView(image: image)
root.addSubview(imageView)

let label = InvertedMaskLabel()
label.text = "Label"
label.frame = imageView.bounds
label.font = .systemFontOfSize(40)
imageView.maskView = label
Run Code Online (Sandbox Code Playgroud)

结果:

标签文本内的图像透明度演示