2013-01-19 8 views
20

Mit dem Code unten, bin ich erfolgreich Maskierung Teil meiner Zeichnung, aber es ist das Gegenteil von dem, was ich maskiert werden soll. Dies maskiert den inneren Teil der Zeichnung, wo ich den äußeren Teil maskieren möchte. Gibt es eine einfache Möglichkeit, diese Maske zu invertieren?iOS invertieren Maske in DrawRect

myPath unten ist ein UIBezierPath.

CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init]; 
CGMutablePathRef maskPath = CGPathCreateMutable(); 
CGPathAddPath(maskPath, nil, myPath.CGPath); 
[maskLayer setPath:maskPath]; 
CGPathRelease(maskPath); 
self.layer.mask = maskLayer; 

Antwort

30

Mit noch ungeradeer Füllung auf der Formebene (maskLayer.fillRule = kCAFillRuleEvenOdd;) Sie können ein großes Rechteck hinzufügen, die den gesamten Rahmen überdeckt und fügen Sie dann die Form, die Sie sind Ausblendung. Dadurch wird die Maske invertiert.

CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init]; 
CGMutablePathRef maskPath = CGPathCreateMutable(); 
CGPathAddRect(maskPath, NULL, someBigRectangle); // this line is new 
CGPathAddPath(maskPath, nil, myPath.CGPath); 
[maskLayer setPath:maskPath]; 
maskLayer.fillRule = kCAFillRuleEvenOdd;   // this line is new 
CGPathRelease(maskPath); 
self.layer.mask = maskLayer; 
+0

Mai werden Sie diese Frage beantworten: http://stackoverflow.com/questions/30360389/ Use-Layer-Maske-to-make-Teile-von-der-Uiview-transparent – confile

+0

Diese Antwort ist großartig und funktioniert einwandfrei. –

+0

wurde CGPathRelease (maskPath) entfernt? es funktioniert aber kann ich ein Speicherleck bekommen? (Swift 2.2, iOS 9.0) Konnte keinen Hinweis darauf finden. – Maik639

7

Basierend auf der angenommenen Antwort, hier ist ein weiteres Mashup in Swift. Ich habe es in eine Funktion aus und machte die invert optional

class func mask(viewToMask: UIView, maskRect: CGRect, invert: Bool = false) { 
    let maskLayer = CAShapeLayer() 
    let path = CGPathCreateMutable() 
    if (invert) { 
     CGPathAddRect(path, nil, viewToMask.bounds) 
    } 
    CGPathAddRect(path, nil, maskRect) 

    maskLayer.path = path 
    if (invert) { 
     maskLayer.fillRule = kCAFillRuleEvenOdd 
    } 

    // Set the mask of the view. 
    viewToMask.layer.mask = maskLayer; 
} 
8

Für Swift 3,0

func mask(viewToMask: UIView, maskRect: CGRect, invert: Bool = false) { 
    let maskLayer = CAShapeLayer() 
    let path = CGMutablePath() 
    if (invert) { 
     path.addRect(viewToMask.bounds) 
    } 
    path.addRect(maskRect) 

    maskLayer.path = path 
    if (invert) { 
     maskLayer.fillRule = kCAFillRuleEvenOdd 
    } 

    // Set the mask of the view. 
    viewToMask.layer.mask = maskLayer; 
}