Is there a class in the Java API that I can utilize to check if a line intersects a shape, given the starting and ending coordinates. I have tried playing around with Line2D objects, but the intersects() function for that class only seems to take in rectangular coordinates and Rectangle2D objects, which doesn't suit my purposes as my shapes can have any number of sides.
问问题
5027 次
3 回答
3
就像@Dan 说的那样,您可以检查您的线是否与您的边界相交,Polygon
但您不必检查与任何两个点创建的每条Polygon
线相交,只需检查您的线与每对两点的相交,例如(p1,p2), (p2,p3), ... , (p(N-1), pN), (pN, p1)
。多边形不是从数组中的所有点组合创建的,而是从 p1 到 p2 的线与从 p2 到 p3 的线相连,依此类推,直到从 pN 到 p1 的线。
这里有一些例子:
Line2D myLine = getMyLine() // some imagine method giving your line
Point2D[] polyPoints = getPolyPoints() // some imagine method giving point of your Polygon
boolean intersect = false;
for (int i = 0; i < polyPoints.length - 1; i++) {
intersect = myLine.intersectsLine(polyPoints[i].getX(), polyPoints[i].getY(), polyPoints[i+1].getX(), polyPoints[i+1].getY());
if (intersect) {
break;
}
}
if (!intersect) {
intersect = myLine.intersectsLine(polyPoints[polyPoints.length - 1].getX(), polyPoints[polyPoints.length - 1].getY(), polyPoints[0].getX(), polyPoints[0].getY());
}
在内部执行此代码后,intersect
您的价值是您的线是否与多边形相交。
如果您接受多边形可以包含一条线的情况,这仍然意味着该线(作为路径)与多边形相交,然后Polygon
从您的点(顶点)创建 java 实例并调用:
if (!intersect) {
intersect = myPolygon.contains(myLine.getP1()) || myPolygon.contains(myLine.getP2());
}
于 2013-02-01T18:33:34.657 回答
1
您可以检查您的线是否与形状中任意 2 个点给出的任何线相交。因此,您迭代形状点并构建 2 个点的任意组合的线。如果这些线段中的任何一条与您的线相交,则您的线与该形状相交。
于 2013-02-01T18:10:13.060 回答