Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two UIBezierPaths intersection as a UIBezierPath

I have two UIBezierPaths, one that represents the polygon of part of an image and the other is a path to be drawn on top of it.

I need to find the intersection between them so that only the point that are inside this intersection area will be colored.

Is there a method in UIBezierPath that can find intersection points - or a new path - between two paths ?

like image 203
Amani Elsaed Avatar asked Feb 23 '17 14:02

Amani Elsaed


2 Answers

I'm not aware of a method for getting a new path that's the intersection of two paths, but you can fill or otherwise draw in the intersection by using the clipping property of each path.

In this example, there are two paths, a square and a circle:

let path1 = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 100, height: 100))
let path2 = UIBezierPath(ovalIn: CGRect(x:50, y:50, width: 100, height: 100))

I make a renderer to draw these, but you could be doing this in drawRect or wherever:

let renderer = UIGraphicsImageRenderer(bounds: CGRect(x: 0, y: 0, width: 200, height: 200))
let image = renderer.image {
    context in
    // You wouldn't actually stroke the paths, this is just to illustrate where they are
    UIColor.gray.setStroke()
    path1.stroke()
    path2.stroke()
    // You would just do this part
    path1.addClip()
    path2.addClip()
    UIColor.red.setFill()
    context.fill(context.format.bounds)
}

The resulting image looks like this (I've stroked each path for clarity as indicated in the code comments, in actual fact you'd only do the fill part):

enter image description here

like image 115
jrturton Avatar answered Sep 18 '22 22:09

jrturton


I wrote a UIBezierPath library that will let you cut a given closed path into sub shapes based on an intersecting path. It'll do essentially exactly what you're looking for: https://github.com/adamwulf/ClippingBezier

NSArray<UIBezierPath*>* componentShapes = [shapePath uniqueShapesCreatedFromSlicingWithUnclosedPath:scissorPath];

Alternatively, you can also just find the intersection points:

NSArray* intersections = [scissorPath findIntersectionsWithClosedPath:shapePath andBeginsInside:nil];
like image 35
adam.wulf Avatar answered Sep 20 '22 22:09

adam.wulf