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; 

在形状图层上填充奇数( 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; 

对于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; } 

基于接受的答案,这里是Swift中的另一个混搭。 我已经把它变成了一个function,并使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; }