How to determine if NSBezierPaths intersect in Cocoa?

I find it difficult to determine how to determine the intersection of two closed NSBezierPath objects in cocoa. I did some research on the Internet and have not found an answer so far.

Here is what I have. enter image description here

I need to write some method that will return true in all of these cases.

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

However, I do not know how to get through all the points of the segment ...

If anyone has any hints or ideas that might help, I would really appreciate it!

+5
source share
2 answers

If you have 2 rectangles of the bezier path and know each of their frames, 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"));

It produces:

enter image description here

In this case, he will record intersects == YES.

+3
source

Here is a pretty quick and clean solution. It also works to test several paths against one, which is good, right?

It works with CGBezier (iOS and MacOS compatible)

• 1 - Create contexts of necessary items

Create a 16-bit, single component (non-alpha) graphics port with the same size as the view .

  • , . .
  • computeContext

16-, ( -) 1 .

  • testContext

• 2 - :

computeContext :

  • ( )
  • , .
  • ,
  • ( computeContext.) testContext - :
CGImageRef clippedPathsImage = CGBitmapContextCreateImage(computeContext);
CGRect     onePixSquare = CGRectMake(0,0,1,1);
CGContextDrawImage(testContext, onePixSquare, clippedPathsImage);

( , . malloc , bitmapContext)

!

long*   data = CGBitmapContextGetData(testContext);  
BOOL    intersects = (*data!=0);
  • , -

  • , , . .

, computeContext, , 25% .

1 , 4 ( 25- , ).

8 . , , 1 . , .

, , , - !

GitHub ;) https://github.com/moosefactory

, , !;)


16 . , , . - bitmapInfo ( ), , float.

-(CGContextRef)createComputeContext
{
    size_t  w = (size_t)self.bounds.size.width;
    size_t  h = (size_t)self.bounds.size.height;
    size_t  nComps = 1;
    size_t  bits   = 16;
    size_t  bitsPerPix  = bits*nComps;
    size_t  bytesPerRow = bitsPerPix*w;    
    CGColorSpaceRef  cs = CGColorSpaceCreateDeviceGray();

    CGContextRef bmContext = CGBitmapContextCreate(NULL, w, h, bits, bytesPerRow, cs, 0);

    return bmContext;
}
+2

All Articles