2016-04-21 11 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 में पाठ How to mask the layer of a view by the content of another view? में के रूप में imageView की एक फ़ॉन्ट रंग की है।

मैं यह कैसे रिवर्स तो के रूप में textLabelimageView से में पाठ निकालते हैं?

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) 
    } 
} 

यह उपवर्ग एक अपारदर्शी रंग (इस उदाहरण में सफेद है, लेकिन केवल अल्फ़ा चैनल मामलों) के साथ अपनी सीमा को भर देता है:

उत्तर

7

UILabel का एक उपवर्ग करें। फिर यह Clear मिश्रण मोड का उपयोग करके टेक्स्ट खींचता है, जो अल्फा चैनल समेत संदर्भ के सभी चैनलों को 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 

परिणाम:

demo of image transparency inside the label text