java.awt.Rectangle. intersection()

房东的猫 提交于 2019-12-04 18:50:29

The opposite corners of your rectangles are (0,10),(5,18) and (3,15),(20,29), so the intersection is (3,15),(5,18), so I think the result is the expected one. Notice the opposite corners of the resultant one are the bottom-right of the first one and the top-left of the second one.

Edit: The way it works is: the starting point is (x,y), and the sides are calculated adding the widthand height to the starting point, so the opposite corner will be (x+width,y+height)

Final note: (0,0) is the upper-left corner of the canvas: Here is an example: (0,0,4,4) and (2,2,4,4) intersection is (2,2,2,2): (2,2) is the upper-left one and (2+2,2+2) is opposite corner

The answer you are getting is correct. The method works like this.

1st Rectangle:

  • X co-ordinates: 0
  • Y co-ordinates: 10
  • Width: 5
  • Height: 8

2nd Rectangle:

  • X co-ordinates: 3
  • Y co-ordinates: 15
  • Width: 17
  • Height: 14

For the intersection the X and Y co-ordinates are same as 2nd rectangle. Width is 5-3=2 and Height is 18-15=3

I also had trouble with this. The way I think about it is that the grid used is inverted on the y axis. Because point 0.0 is at the top left of the screen with point 0,1 being below rather than above that point you can get the answer you are expecting by inverting the the y axis in your original code.

For example.

public void printIntersection(){ 
Rectangle r1 = new Rectangle(0, 10 * -1 , 5, 8);
Rectangle r2 = new Rectangle(3, 15 * -1, 17, 14);
Rectangle r3 = r1.intersection(r2);

System.out.println(r1);
System.out.println(r2);
System.out.println(r3);

}

This should give you the answer you are expecting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!