2016-04-21 29 views
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的字體顏色,如How to mask the layer of a view by the content of another view?

如何扭轉這種以刪除文中textLabelimageView

回答

7

使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