标签的反向图层蒙版

8

如何反转标签的遮罩层?我有一个 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相同的字体颜色,就像如何通过另一个视图的内容来屏蔽视图的层?

我该怎么做才能将textLabel中的文本imageView移除,即反转上述操作?

2个回答

13

创建一个继承自 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 通道有影响)。然后使用“清除”混合模式绘制文本,该混合模式将上下文的所有通道(包括 alpha 通道)全部设置回 0。

播放示例:

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

结果:

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


你能帮我吗? - Hector

0

最近我需要实现这个功能,而且语法有些变化,这里提供@RobMayoff的优秀答案的Swift 4.x版本。带有Swift Playground的演示/GitHub存储库位于此处

(如果您点赞了这篇文章,请也点赞他的原始回答:))

演示该技术的Playground。方法InvertedMaskLabel内的drawRect是秘密酱汁。

import UIKit
import PlaygroundSupport

// As per https://dev59.com/Gpbfa4cB1Zd3GeqPrktn

class InvertedMaskLabel: UILabel {

    override func drawText(in rect: CGRect) {

        guard let context = UIGraphicsGetCurrentContext() else { return }

        context.saveGState()
        UIColor.white.setFill()
        UIRectFill(rect) // fill bounds w/opaque color
        context.setBlendMode(.clear)
        super.drawText(in: rect) // draw text using clear blend mode, ie: set *all* channels to 0
        context.restoreGState()
    }
}

class TestView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)

        backgroundColor = .green

        let image = UIImage(named: "tr")
        let imageView = UIImageView(image: image)
        imageview.frame = bounds
        addSubview(imageView)

        let label = InvertedMaskLabel()
        label.text = "Teddy"
        label.frame = imageView.bounds
        label.font = UIFont.systemFont(ofSize: 30)
        imageView.mask = label
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

let testView = TestView(frame: CGRect(x: 0, y: 0, width: 400, height: 500))
PlaygroundPage.current.liveView = testView

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接