Skip to content

Commit 70c2969

Browse files
authored
Simplify Rectangle.intersects (#302)
Simplify and optimize the intersects checking method of Rectangle. Also align the behavior of Rectangle.intersect for empty intersections. Signed-off-by: Martin Jobst <[email protected]>
1 parent 1592a00 commit 70c2969

File tree

2 files changed

+12
-7
lines changed

2 files changed

+12
-7
lines changed

org.eclipse.draw2d.tests/src/org/eclipse/draw2d/test/RectangleTest.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,14 @@ public void testIntersects() throws Exception {
260260
assertFalse(rectangle1.intersects(new Rectangle(-100, -100, 10, 10)));
261261
//
262262
assertFalse(rectangle1.intersects(new Rectangle(0, 0, 5, 10)));
263+
//
264+
assertFalse(rectangle1.intersects(new Rectangle(15, 20, 0, 10)));
265+
assertFalse(rectangle1.intersects(new Rectangle(15, 20, 10, 0)));
266+
//
267+
Rectangle rectangle3 = new Rectangle(0, 30, 0, 40);
268+
assertFalse(rectangle3.intersects(rectangle3));
269+
//
270+
assertFalse(rectangle3.intersects(new Rectangle(0, 30, 100, 10)));
263271
}
264272

265273
@SuppressWarnings("static-method")

org.eclipse.draw2d/src/org/eclipse/draw2d/geometry/Rectangle.java

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -725,7 +725,7 @@ public Rectangle intersect(Rectangle rect) {
725725
int x2 = Math.min(x + width, rect.x() + rect.width());
726726
int y1 = Math.max(y, rect.y());
727727
int y2 = Math.min(y + height, rect.y() + rect.height());
728-
if (((x2 - x1) < 0) || ((y2 - y1) < 0)) {
728+
if (((x2 - x1) <= 0) || ((y2 - y1) <= 0)) {
729729
return setBounds(0, 0, 0, 0); // no intersection
730730
}
731731
return setBounds(x1, y1, x2 - x1, y2 - y1);
@@ -739,12 +739,9 @@ public Rectangle intersect(Rectangle rect) {
739739
* @since 2.0
740740
*/
741741
public boolean intersects(Rectangle rect) {
742-
int x1 = Math.max(x, rect.x());
743-
int x2 = Math.min(x + width, rect.x() + rect.width());
744-
int y1 = Math.max(y, rect.y());
745-
int y2 = Math.min(y + height, rect.y() + rect.height());
746-
747-
return (((x2 - x1) > 0) && ((y2 - y1) > 0));
742+
return width > 0 && height > 0 && rect.width() > 0 && rect.height() > 0 //
743+
&& x < rect.x() + rect.width() && rect.x() < x + width //
744+
&& y < rect.y() + rect.height() && rect.y() < y + height;
748745
}
749746

750747
/**

0 commit comments

Comments
 (0)