【发布时间】:2018-04-18 00:51:03
【问题描述】:
所以我正在编写一个方法来获取与多边形相交的所有点。
这是我的多边形。
Point point = new Point(1, 1);
points.add(point);
point = new Point(99, 99);
points.add(point);
point = new Point(199, 1);
points.add(point);
polygon = new Polygon(points);
这是我的测试用例。
List<Point> expected = new ArrayList<Point>();
Point p = new Point();
p.setX(50);
p.setY(50);
expected.add(p);
Point start = new Point(1, 99);
Point end = new Point(99, 1);
Line aLine = new Line(start, end);
List<Point> intersection = new ArrayList<>(polygon.getIntersections(aLine)); //Normal Case
assertNotNull(intersection);
assertEquals(expected,intersection);
我认为这很容易解释,但 Point 是一个具有 x、y、z 值的类,而 Line 只是 4 个点,前 2 个点是一个点,后 2 个点是另一个点,它们只是连接.
这是我获取所有交叉点的方法。
public List<Point> getIntersections(Crossable aLine) {
List<Point> listOfIntersections = new ArrayList<Point>();
Point intersectedPoint = new Point();
for(int i = 0; i < this.points.size()-1; i++) {
Point firstPoint = this.points.get(i);
for(int j = i + 1; j < this.points.size(); j++) {
Point secondPoint = this.points.get(j);
Line2D line1 = new Line2D.Double(
firstPoint.getX(), firstPoint.getY(),
secondPoint.getX(), secondPoint.getY()
);
Line2D line2 = new Line2D.Double(
((Line) aLine).getStart().getX(),((Line) aLine).getStart().getY(),
((Line) aLine).getEnd().getX(), ((Line) aLine).getEnd().getY()
);
boolean result = line2.intersectsLine(line1);
if(!result) {
}
else {
final double x1, y1, x2,y2, x3,y3, x4,y4;
x1 = firstPoint.getX();
y1 = firstPoint.getY();
x2 = secondPoint.getX();
y2 = secondPoint.getY();
x3 = ((Line) aLine).getStart().getX();
y3 = ((Line) aLine).getStart().getY();
x4 = ((Line) aLine).getEnd().getX();
y4 = ((Line) aLine).getEnd().getY();
double denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);
if (denom == 0.0) { // Lines are parallel.
}
double ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denom;
double ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denom;
if (ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f) {
// Get the intersection point.
intersectedPoint.setX(x1 + ua*(x2 - x1));
intersectedPoint.setY(y1 + ua*(y2 - y1));
listOfIntersections.add(intersectedPoint);
}
}
}
}
if(listOfIntersections.size() == 0) {
return null;
}
return listOfIntersections;
}
由于某种原因而不是返回 这是多边形的正确交集,它返回 和 对此有什么建议吗?谢谢。
【问题讨论】: