Reputation: 723
I am making a CGPoint and a CGPathRef then trying to find if the CGPoint is inside the CGPathRef. Here is the code:
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 0, 0);
CGPathMoveToPoint(path, NULL, 200, 0);
CGPathMoveToPoint(path, NULL, 200, 200);
CGPathMoveToPoint(path, NULL, 0, 200);
CGPathCloseSubpath(path);
CGPoint hitPoint = CGPointMake(77, 77);
if ( CGPathIsEmpty(path) )
NSLog(@"Path Is Empty!");
else
{
if ( CGPathIsRect(path, NULL) )
NSLog(@"Path is a Rectangle!");
else
{
NSLog(@"Path is NOT a Rectangle!");
if (CGPathContainsPoint(path, NULL, hitPoint, FALSE)) // FALSE or TRUE - same result
NSLog(@"Hit Point Inside: x=%f, y=%f", hitPoint.x, hitPoint.y);
else
NSLog(@"Hit Point Outside: x=%f, y=%f", hitPoint.x, hitPoint.y);
}
}
The output reads:
Path is NOT a Rectangle!
Hit Point Outside: x=77.000000, y=77.000000
The path obviously is a rectangle and the point is inside the closed path. Please clue me in on what I am doing wrong here.
Upvotes: 0
Views: 714
Reputation: 385600
CGRectIsPath
only returns true if the path was created by CGPathCreateWithRect
(with a transform
parameter that doesn't rotate or skew the rectangle), or if the path was created by CGPathCreateMutable
and had a single rectangle added to it with CGPathAddRect
.
It would be much more work for it to figure out whether any arbitrary path is exactly a rectangle. The path might contain bezier curve segments that are actually straight lines, or sides that are built from consecutive straight line segments.
If you need to detect whether any arbitrary path is actually just a rectangle, you will have to do it yourself using CGPathApply
. It will be complicated.
As for why your point-inside test isn't working: you need to use CGPathAddLineToPoint
to create the sides of your rectangle:
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 0, 0);
CGPathAddLineToPoint(path, NULL, 200, 0);
CGPathAddLineToPoint(path, NULL, 200, 200);
CGPathAddLineToPoint(path, NULL, 0, 200);
CGPathCloseSubpath(path);
Upvotes: 1