开发者

How to determine if a square is inside a rectangle?

Higuys,

In Java, I wonder how can I determine if a square is inside a rectangle, or touching at the edges or touching at one corner, if these are given:

  • x and y coordinates of the square, width of the square
  • x and y coordinates of the rectangle, width & length of the rectangle

I know I have to use Math.abs() 开发者_高级运维and find the x and y coordinate differences, but I could not formulate the problem mathematically.

All data types are doubles, by the way.

Even if you don't know Java, your ideas about mathematical formulation of this problem would be much appreciated.

Thanks in advance.


Irrespective of the language used, you can determine it by the following naive algorithm.

Test to see if all the points of the square lie inside the rectangle. You may want to define the function in such a way that, if a point of square touches the line of rectangle, it is considered to be inside.


Just check to see if the top left corner falls within the bounds of the rectangle, and then compare the lengths of the width and height. The following is a simplified answer, and as you indicated, you'll need to implement Math.Abs() to correct for negative coordinates.

bool IsInside(Square s, Rectangle r) {
    if (s.x < r.x) return false;
    if (s.y > r.y) return false;
    if ((r.Width - r.x) < (s.Width - s.x)) return false;
    if ((r.Height - r.y) < (s.Width - s.y)) return false;

    return true;
}


Since you have not tagged this question as homework, I assume you can use the standard library methods:

static boolean isSquareInRectangle(sx, sy, sw, rx, ry, rw, rh) {
    Rectangle2D s = new Rectangle2D.Double(sx, sy, sw, sw),
                r = new Rectangle2D.Double(rx, ry, rw, rh);
    return r.contains(s);
}


Is this homework?

The gist of the solution is to check the boundaries. Like:

boolean inside=square.x>=rectangle.x && square.x+square.width<=rectangle.x+rectangle.width
  && square.y>=rectangle.y && square.y+square.width<=rectangle.y+rectangle.height;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜