如何反转标签的遮罩层?我有一个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
上面的内容使textLabel中的文本具有imageView的字体颜色,如How to mask the layer of a view by the content of another view?所示.
如何撤消此操作以从imageView中删除textLabel中的文本?
解决方法
创建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)
- }
- }
此子类用不透明的颜色填充其边界(在此示例中为白色,但只有alpha通道很重要).然后,它使用“清除混合”模式绘制文本,该模式简单地将上下文的所有通道设置为0,包括Alpha通道.
游乐场演示:
- let root = UIView(frame: CGRectMake(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
结果: