从CGPath中剪除/减去CGPath?

11

我在 CAShapeLayer 上做了一些带有两个圆形的 CGPath 多边形。

我能像这样修剪/减去路径吗?

enter image description here


简短回答:不行。长话短说:你可以,但是很难。 - David Rönnqvist
谢谢 :) 我可以通过添加图层蒙版作为后备来完成它,但我想抑制光栅化通道,更喜欢数学方法。 - Geri Borbás
谢谢。这是在设计过程中制作的,但非常适合这个问题。 :) - Geri Borbás
2个回答

6

不必进行数学计算,可以在绘制时使用kCGBlendModeClear来获得结果。

// Create the poly.
CGContextBeginPath(context);
CGContextMoveToPoint       (context, a_.x, a_.y);
CGContextAddLineToPoint    (context, b_.x, b_.y);
CGContextAddLineToPoint    (context, c_.x, c_.y);
CGContextAddLineToPoint    (context, d_.x, d_.y);
CGContextClosePath(context);

// Draw with the desired color.
CGContextSetFillColorWithColor(context, self.color.CGColor);
CGContextFillPath(context);

// Create a circle.
CGContextBeginPath(context);
CGContextAddEllipseInRect(context, (CGRect){
    b_.x - self.radius,
    b_.y - self.radius,
    self.radius * 2.0,
    self.radius * 2.0 });
CGContextClosePath(context);

// Draw with Clear (!) blend mode.
CGContextSetBlendMode(context, kCGBlendModeClear);
CGContextSetFillColorWithColor(context, self.color.CGColor);
CGContextFillPath(context);

2

根据Geri的回答,使用Swift 5

context.addPath(path1) // your original CGPath
context.setFillColor(color1) // your color
context.fillPath()
        
context.addPath(path2) // your clearing CGPath
context.setBlendMode(.clear) // draw with clear mode
context.fillPath()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接