Search code examples
ioscore-graphicsuibezierpathcgpath

Clipping a CGPathRef or UIBezierPath


Given that I have a CGPathRef, or a UIBezierPath, or some other equivalent iOS representation, are there built in library functions that I can use to compute a clip of this object for me?

  • I specifically need to clip against an axis aligned rectangle.
  • It'd be very cool to be able to clip against another arbitrary path.
  • It'd be even more cool to be able to compute boolean operations on paths: union, difference, intersection (clipping being the intersection operation).

Note To clarify, I am not asking to be able to draw a path with clipping. I want to obtain an actual clipped path, as a new path.


Solution

  • Check out my similar answer to this other question. I wrote a library that will let you calculate the intersections between any two UIBezierPath and calculate the clipped path between them. The library is at https://github.com/adamwulf/ClippingBezier.

    While that other questions deals with the intersection of shapes, you can also simply split two paths into component pieces.

    NSArray* clippedPathSegments = [UIBezierPath redAndGreenAndBlueSegmentsCreatedFrom:path1 bySlicingWithPath:path2 andNumberOfBlueShellSegments:NULL];
    

    That method has a bit of an awkward name, it's used internally for the better named uniqueShapesCreatedFromSlicingWithUnclosedPath: method, but should do what you want.