java.awt.Rectangle中。路口() [英] java.awt.Rectangle. intersection()
问题描述
我是开发一个任务时,我决定用java.awt.Rectangle中计算两个矩形的交集。
I was developing an task when I decided to use java.awt.Rectangle to calculate the intersection between two rectangles.
我意识到,输出跟我想象的不同。我不知道,如果我知道这种方法是如何工作或没有。
I realised that the output is different from what I expected. I'm not sure if I understood how this method works or not.
有关在这里的例子中的值 java.awt.Rectangle中的[X = 0,Y = 10,宽度= 5,高度= 8]
java.awt.Rectangle中的[X = 3,Y = 15,宽度= 17,身高= 14]
For the values in the example here
java.awt.Rectangle[x=0,y=10,width=5,height=8]
java.awt.Rectangle[x=3,y=15,width=17,height=14]
我希望路口是 java.awt.Rectangle中的[X = 3,Y = 10,宽度= 2,身高= 8]
但是程序打印 java.awt.Rectangle中的[X = 3,Y = 15,宽度= 2,身高= 3]
,而不是!
I expect the intersection to be java.awt.Rectangle[x=3,y=10,width=2,height=8]
but the program prints java.awt.Rectangle[x=3,y=15,width=2,height=3]
instead!
这是我的code:
public void printIntersection(){
Rectangle r1 = new Rectangle(0, 10, 5, 8);
Rectangle r2 = new Rectangle(3, 15, 17, 14);
Rectangle r3 = r1.intersection(r2);
System.out.println(r1);
System.out.println(r2);
System.out.println(r3);
}
谁能帮我通过指出什么我在这里丢失?
Can anyone help me by pointing out what am I missing here?
更新:
我混乱的根源在于code对待(X,Y)值在构造函数中的左下角,而类文档表明,他们是左上角!
UPDATE: The source of my confusion is that the code treats the (x,y) values in the constructor as the bottom-left corner, while the class doc suggests that they are the upper-left corner!
推荐答案
您矩形的对角是(0,10),(5,18)
和(3,15),(20,29)
,所以交集(3,15),(5,18)
,所以我觉得结果是所预期的。注意到所得之一的相对的角是第一个和左上角的第二个的
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.
编辑:它的工作原理是:起点是(X,Y)
,并且双方都计算添加widthand高度出发点,所以对面角落里将(X +宽度,Y +高)
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)
最后说明:(0,0)是画布的左上角:
这里是一个例子:(0,0,4,4)和(2,2,4,4)交点(2,2,2,2):(2,2)是左上酮和(2 + 2,2 + 2)是对角
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
这篇关于java.awt.Rectangle中。路口()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!