2013-01-19 42 views
20

下面的代碼,我成功地掩蓋了我的繪圖的一部分,但它是我想要蒙版的反面。這掩蓋了圖形的內部部分,我想掩蓋外部。有沒有簡單的方法來反轉這個面具?iOS反轉蒙版在drawRect

myPath以下是UIBezierPath

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

回答

30

隨着甚至形狀層(maskLayer.fillRule = kCAFillRuleEvenOdd;)可以添加一個大的矩形覆蓋整個幀,然後添加你屏蔽掉的形狀在奇數填充。這將實際上反轉掩模。

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

可能是你能回答這個問題太:http://stackoverflow.com/questions/30360389/使用圖層蒙版製作零件的uiview透明 – confile

+0

這個答案很棒,並且完美無瑕。 –

+0

被CGPathRelease(maskPath)刪除了嗎?它的工作,但我可以得到一個內存泄漏? (Swift 2.2,iOS 9.0)找不到對它的任何引用。 – Maik639

7

根據接受的答案,這裏是Swift中的另一個mashup。我已經把它做成了功能並提出了invert可選

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

對於雨燕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; 
}