2013-01-19 19 views
20

Con il codice seguente, sto mascherando con successo parte del mio disegno, ma è l'inverso di ciò che voglio mascherato. Questo maschera la parte interna del disegno, dove vorrei mascherare la parte esterna. C'è un modo semplice per invertire questa maschera?Maschera invertita iOS in drawRect

myPath di seguito è un UIBezierPath.

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

risposta

30

Con anche riempimento dispari sul livello forma (maskLayer.fillRule = kCAFillRuleEvenOdd;) si può aggiungere un grande rettangolo che copre l'intero telaio e quindi aggiungere la forma si mascheratura. Questo in effetti invertirà la maschera.

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

Può essere che si può rispondere a questa domanda anche: http://stackoverflow.com/questions/30360389/ use-layer-mask-to-make-parts-of-the-uiview-transparent – confile

+0

Questa risposta è ottima e funziona in modo impeccabile. –

+0

è stato rimosso CGPathRelease (maskPath)? funziona, ma posso ottenere una perdita di memoria? (Swift 2.2, iOS 9.0) Impossibile trovare alcun riferimento ad esso. – Maik639

7

In base alla risposta accettata, ecco un altro mashup in Swift. Ho fatto in una funzione e fatto la invert opzionale

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

per 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; 
}