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 protected])

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [EMAIL PROTECTED]

Reply via email to