2016-04-21 17 views
8

Jak odwrócić warstwę maski dla etykiety? Mam textLabel, którego używam jako maskę na imageView który zawiera dowolny obraz w następujący sposób:Maska odwrotnej warstwy dla etykiety

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 

Powyższe sprawia, że ​​tekst w textLabel mieć kolor czcionki w imageView jak w How to mask the layer of a view by the content of another view?.

Jak mogę odwrócić tak aby usunąć tekst w textLabelodimageView?

Odpowiedz

7

Dodać podklasę 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) 
    } 
} 

Podklasa wypełnia swoje granice z nieprzezroczystej barwy białej (w tym przykładzie, ale tylko w dziedzinie kanał alfa). Następnie rysuje tekst za pomocą trybu mieszania Clear, który po prostu ustawia wszystkie kanały kontekstu z powrotem na 0, w tym kanał alfa.

zabaw demo:

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 

Wynik:

demo of image transparency inside the label text