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

上面的内容使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

结果:

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...