check if point is within a given distance of a rectangle?
i write a boolean that checks to see if a point is within a given distance of a filled rectangle
the rectangle is defined by its bottom left point and i开发者_StackOverflow中文版ts width and height
Is this homework? Anyway. Assuming you mean proper distance, as in "distance between the closest point to the rectangle":
int IsWithinDistance(int pointX, int pointY, int rectX, int rectY, int rectWidth, int rectHeight, int distanceThreshold)
{
int x2 = rectX + rectWidth;
int y2 = rectY + rectHeight;
int xDiff = (pointX < rectX) ? rectX - pointX : pointX - x2;
int yDiff = (pointY < rectY) ? rectY - pointY : pointY - y2;
int distance2;
xDiff = (xDiff < 0) ? 0 : xDiff;
yDiff = (yDiff < 0) ? 0 : yDiff;
distance2 = xDiff * xDiff + yDiff * yDiff;
return distance2 < (distanceThreshold * distanceThreshold);
}
To find the distance between any two points you can use this:
CGFloat distanceBetweenPoints(CGPoint pt1, CGPoint pt2)
{
CGFloat dx = pt2.x - pt1.x;
CGFloat dy = pt2.y - pt1.y;
return sqrt(dx*dx + dy*dy);
}
You could use this to find the distance to the center of the rectangle or to another point if you prefer.
CGFloat distanceToRect = distanceBetweenPoints( aPoint, aRect.center );
My approach would be something like this. (This assumes y increases as you go up.)
BOOL IsWithinDistance(POINT pt, RECT rc, int distance)
{
return (pt.x > (rc.left - distance) &&
pt.x < (rc.right + rc.width + distance) &&
pt.y > (rc.bottom - distance) &&
pt.y < (rc.bottom + rc.height + distance));
}
精彩评论