我正在编写一个Rectangle
类,该类包括一个基于给定点分别位于矩形的内部,上方还是外部而返回+ 1/0 / -1的方法。
我正在计算该点相对于矩形4个边的位移。虽然“内部”的条件很简单,但“在矩形上”的条件有8个条件。有没有更好,更优雅的方式来处理“矩形”条件?
public class Rectangle {
private final Point bottomLeft;
private final Point topLeft;
private final Point topRight;
private final Point bottomRight;
//Other code here.
public int checkIfPointInside(Point point) {
final int leftDisplacement = point.getX() - bottomLeft.getX();
final int topDisplacement = point.getY() - topLeft.getY();
final int rightDisplacement = point.getX() - topRight.getX();
final int bottomDisplacement = point.getY() - bottomRight.getY();
if (leftDisplacement > 0 && topDisplacement < 0 && rightDisplacement < 0 && bottomDisplacement > 0) {
return 1;
}
if ((leftDisplacement == 0 && topDisplacement < 0 && rightDisplacement < 0 && bottomDisplacement > 0)
|| (leftDisplacement == 0 && topDisplacement == 0 && rightDisplacement < 0 && bottomDisplacement > 0)
|| (leftDisplacement > 0 && topDisplacement == 0 && rightDisplacement < 0 && bottomDisplacement > 0)
|| (leftDisplacement > 0 && topDisplacement == 0 && rightDisplacement == 0 && bottomDisplacement > 0)
|| (leftDisplacement > 0 && topDisplacement < 0 && rightDisplacement == 0 && bottomDisplacement > 0)
|| (leftDisplacement > 0 && topDisplacement < 0 && rightDisplacement == 0 && bottomDisplacement == 0)
|| (leftDisplacement > 0 && topDisplacement < 0 && rightDisplacement < 0 && bottomDisplacement == 0)
||(leftDisplacement == 0 && topDisplacement < 0 && rightDisplacement == 0 && bottomDisplacement == 0)) {
return 0;
}
return -1;
}
}
请注意,第二个条件是仅检查一侧或任意两个相邻侧的位移是否为0。
答案 0 :(得分:5)
您正在测试内部是否返回1。一切正常。
但是随后您测试矩形上的 是否返回0。太复杂了。
相反,测试 outside 是否返回-1。
if (leftDisplacement > 0 && rightDisplacement < 0 && bottomDisplacement > 0 && topDisplacement < 0) {
return 1; // Inside
}
if (leftDisplacement < 0 || rightDisplacement > 0 || bottomDisplacement < 0 || topDisplacement > 0) {
return -1; // Outside
}
return 0; // On Rectangle