2013-01-19 11 views
20

Za pomocą poniższego kodu pomyślnie maskuję część mojego rysunku, ale jest to odwrotność tego, co chcę zamaskować. To maskuje wewnętrzną część rysunku, gdzie chciałbym zamaskować zewnętrzną część. Czy istnieje prosty sposób na odwrócenie tej maski?Maska odwracająca iOS w drawRect

myPath poniżej to UIBezierPath.

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

Odpowiedz

30

jeszcze nieparzystej nadzieniem na warstwie kształtu (maskLayer.fillRule = kCAFillRuleEvenOdd;) można dodać duży prostokąt, który obejmuje całą ramkę, a następnie dodać kształt jesteś maskowania. To w efekcie zmieni maskę.

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

Może można odpowiedzieć na to pytanie też: http://stackoverflow.com/questions/30360389/ use-layer-mask-to-make-parts-of-the-uiview-transparent – confile

+0

Ta odpowiedź jest świetna i działa bezbłędnie. –

+0

Usunięto CGPathRelease (maskPath)? działa, ale czy mogę dostać wyciek pamięci? (Swift 2.2, iOS 9.0) Nie można znaleźć żadnego odniesienia do niego. – Maik639

7

Na podstawie przyjętej odpowiedzi, oto kolejny mashup w Swift. Zrobiłem go do funkcji i sprawił, że invert opcjonalnego

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

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