开发者

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));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜