微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

结果:

原文地址:https://www.jb51.cc/iOS/333901.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐