[英]Reverse layer mask for label
如何反转标签的遮罩层? 我有一个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
?
创建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
结果:
由于我最近需要实现这一点并且语法发生了一些变化,因此这是@RobMayoff 出色答案的Swift 4.x 版本。 带有 Swift Playground 的演示/GitHub 存储库位于此处。
(如果您对此赞不绝口,请也支持他的原始答案:))
展示技术的操场。 InvertedMaskLabel
中的drawRect
方法有秘诀。
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()
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.