Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if NSBezierPaths intersect in Cocoa?

I'm having a hard time figuring out how to determine the intersection of two NSBezierPath closed objects in cocoa. I did some research online and couldn't find the answer so far.

Here is what I have. enter image description here

I need to write some kind of a method that would return true in all of these cases.

What I was thinking so far is to flatten the rectangle by using bezierPathByFlatteningPath and then take each element (as a line segment) using elementAtIndex: associatedPoints: to go through every point in it and checking if the second object (rectangle or ellipse) contains that point (using containsPoint:).

However, I don't know how to go through all the points of a segment...

If anyone has any hint or idea that might help I would really appreciate it!

like image 260
Eugene Gordin Avatar asked Mar 22 '13 19:03

Eugene Gordin


1 Answers

If you have 2 bezier path rectangles and know each of their frames, then you can use NSIntersectsRect():

NSRect rect1 = NSMakeRect(20.0, 150.0, 300.0, 100.0);
NSRect rect2 = NSMakeRect(100.0, 100.0, 100.0, 200.0);

[[NSColor redColor] set];

[NSBezierPath strokeRect:rect1];
[NSBezierPath strokeRect:rect2];

BOOL intersects = NSIntersectsRect(rect1, rect2);

NSLog(@"intersects == %@", (intersects ? @"YES" : @"NO"));

Produces:

enter image description here

In this case, it would log intersects == YES.

like image 121
NSGod Avatar answered Sep 22 '22 23:09

NSGod