Pergunta

There is a Rectangle2D.Double object named rect2d and a Line2D.Double object named line2d.

Please consider the following situation:

enter image description here

Question 1:

What will this line of code return?

boolean intersect = line2d.getBounds2D().intersects(rect2d);

Question 2:

The width/thickness of line2d is 1 pixel. It's height/length is 20 pixels.

What would be the width and height values of the Rectangle2D object returned by line2d.getBounds2D()?

Foi útil?

Solução

It will return:

false
java.awt.geom.Rectangle2D$Double[x=10.0,y=10.0,w=0.0,h=20.0]

With this code:

Line2D.Double line2d = new Line2D.Double(10, 10, 10, 30);
Rectangle2D.Double rect2d = new Rectangle2D.Double(0, 0, 100, 100);

boolean intersect = line2d.getBounds2D().intersects(rect2d);
System.out.println(intersect);
System.out.println(line2d.getBounds2D());

Although, it's useless to say that a line is 1 pixel, because it can't be other way using Line2D.Double. Indeed, for Java, this vertical line as a 0-pixel width boundary, so that's why it will never intersect with any other shape. With a non-vertical and non-horizontal line, its bounds intersect.

Do not use bounds to compute intersection, but directly the Shape:

boolean intersect = line2d.intersects(rect2d);

You may check RectangularShape.intersects() Javadoc for more information on how this method computes intersection.

Outras dicas

From the docs, here and here, the first would return false and the second a bounding box at least the size of the dimensions of the line.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top