Java-多边形和线的交点
是否有任何函数可以提供 Polygon
和 Line2D
的交点?
我有一个多边形和一个我知道相交的线段,我想要交点的实际值而不是布尔答案。
Is there any function that will give me the intersection point of a Polygon
and Line2D
?
I have a Polygon and a line segment that I know intersect I want the actual value of the intersection point not a boolean answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
给你。有趣的方法是 getIntersections 和 getIntersection。前者解析所有多边形线段并检查交点,后者进行实际计算。请记住,可以认真优化计算,并且不检查除以 0 的情况。这也仅适用于多边形。如果您引入三次和二次曲线的计算,它可以适应其他形状。假设使用 Line2D.Double 而不是 Line2D.Float。集合用于避免重复点(可能出现在多边形角交叉点上)。
请不要在没有进行广泛测试的情况下使用它,因为我刚刚将其快速组装在一起,并且不确定它是否完全正确。
Here you are. The interesting methods are getIntersections and getIntersection. The former parses over all polygon segments and checks for intersections, the latter does the actual calculation. Do keep in mind that the calculation can be seriously optimized and doesn't check for division by 0. This will also work only for polygons. It could be adapted to work with other shapes if you introduce calculations for cubic and quadratic curves. It is assumed that Line2D.Double is used instead of Line2D.Float. A Set is used to avoid duplicate points (might occur on polygon corner intersections).
Please don't use this without extensive testing, since I've just hacked it together quickly and am not sure it's completely sound.
有
java.awt.geom.Area.intersect(Area)
使用构造函数Area(Shape)
与您的 Polygon 并将您的Line2D
传递为要相交的区域将为您提供相交的区域。There is
java.awt.geom.Area.intersect(Area)
using the constructorArea(Shape)
with your Polygon and passing yourLine2D
as an Area to intersect will give you the Area which is intersected.我使用了这种方法并取得了巨大成功:
With great success, i used this approach:
您需要记住它可能在多个地方相交。
我们将多边形的线段称为 P,将实线段称为 L。
我们求出每条线的斜率(斜率为 m)
求出每条线的 y 截距
您可以通过以下方式求解 x 值:
然后将 X 代入 1得到 Y 的方程
如下是算法和结果的实现版本
:
You need to bear in mind that it might intersect at multiple places.
Let's call the line segment of the polygon P and the real line segment L.
We find the slope of each line (slope is m)
Find the y intercept of each line
You can solve for the x value with:
Then plug that X into one of the equations to get the Y
Here's an implemented version of the algorithm
and results:
如果您不限于使用Polygon和Line2D对象,我建议使用JTS。
简单的代码示例:
结果是:
If you are not restricted to use the Polygon and Line2D Objects I would recommend to use JTS.
Simple code example:
Result is: