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.
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.
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.If you are not restricted to use the Polygon and Line2D Objects I would recommend to use JTS.
Simple code example:
Result is:
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.
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 // y = mx+b where b is y-intercept bl = ly1 - (ml*lx1); bp = py1 - (pl*px1);
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:
With great success, i used this approach: