标签的反向图层蒙版

时间:2016-04-21 03:15:59

标签: ios uilabel

如何反转标签的遮罩层?我有一个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中的文字的字体颜色与How to mask the layer of a view by the content of another view?中的imageView相同。

如何撤消此操作以便删除 textLabel 中的文字 imageView

2 个答案:

答案 0 :(得分:9)

创建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通道很重要)。然后它使用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

结果:

demo of image transparency inside the label text

答案 1 :(得分:0)

由于我最近需要实现此功能,并且语法有所更改,因此这里是@RobMayoff的出色答案的 Swift 4.x版本。带有here的Swift Playground的演示/ GitHub存储库。

(如果您对此表示赞成,请也对他的原始答案也表示赞成:))

一个演示该技术的游乐场。 drawRect内部的方法InvertedMaskLabel具有秘密调味。

import UIKit
import PlaygroundSupport

// As per https://stackoverflow.com/questions/36758946/reverse-layer-mask-for-label

class InvertedMaskLabel: UILabel {

    override func drawText(in rect: CGRect) {

        guard let context = UIGraphicsGetCurrentContext() else { return }

        context.saveGState(context)
        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(context)
    }
}

class TestView: UIView {

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

        backgroundColor = .green

        let image = UIImage(named: "tr")
        let imageView = UIImageView(image: image)
        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()
testView.frame = CGRect(x: 0, y: 0, width: 400, height: 500)
PlaygroundPage.current.liveView = testView