java rectangle 单位,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.

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]

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!

here is my 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?

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!

解决方案

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

zBUC0.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值