Trim/subtract CGPath from CGPath?
Asked Answered
M

2

11

I have some CGPath (a poly with two circle) carried out on a CAShapeLayer.

Can I trim/subtract paths like this?

enter image description here

Melvamelvena answered 14/10, 2013 at 13:24 Comment(3)
Short answer: No. Long answer: You can but it's pretty hard.Balling
Thanks :) I can do it with by adding layer mask as a fallback, but I wanted to supress rasterization passes, would prefer math.Hanley
Thanks there. It was made during design process, but was a perfect fit for this question. :)Hanley
M
6

Instead of do the math, the result can be achieved at drawing time using 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);
Melvamelvena answered 14/10, 2013 at 17:55 Comment(0)
C
2

Based on Geri's answer, using 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()
Conjoint answered 10/7, 2021 at 18:48 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.