Re: CGPoint and CGRect
Re: CGPoint and CGRect
- Subject: Re: CGPoint and CGRect
- From: Greg Titus <email@hidden>
- Date: Fri, 21 Nov 2008 15:33:02 -0800
On Nov 21, 2008, at 3:19 PM, DKJ wrote:
I want to determine whether a line between two CGPoints in a view
intersects with a given CGRect. There's nothing in the CGGeometry
reference that does this specifically, and I don't yet see how to
use the functions that are there to figure this out.
Before I dust off my Euclid (a rare first edition), has anyone got a
quick solution? It seems the sort of thing that would be handy in
many situations.
dkj
BOOL lineIntersectsRect(CGPoint a, CGPoint b, CGRect rect)
{
float lineSlope = (b.y - a.y) / (b.x - a.x);
float yIntercept = a.y - lineSlope * a.x;
float leftY = lineSlope * NSMinX(rect) + yIntercept;
float rightY = lineSlope * NSMaxX(rect) + yIntercept;
if (leftY >= NSMinY(rect) && leftY <= NSMaxY(rect))
return YES;
if (rightY >= NSMinY(rect) && rightY <= NSMaxY(rect))
return YES;
return NO;
}
Here's something I just wrote in email (so may be totally wrong), but
basically you determine the slope and y-intercept of the line formed
by the two points, then see where that line's Y-position would be on
each of the left and right sides of the rectangle. If the Y-position
hits the left or right edges of the rect, then the line intersects the
rect.
Note that this is line intersection, not line _segment_ intersection.
If the line doesn't extend beyond the two points given, you'll need a
couple extra checks in this code.
Hope this helps,
- Greg
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden