Java examples for java.lang:Math Geometry Line
intersect Line Segment With Polygon
import java.awt.geom.*; import java.util.*; public class Main{ public static double[][] intersectLineSegmentWithPolygon(double x1, double y1, double x2, double y2, double[][] polygon) { java.util.List intersectionList = new java.util.LinkedList(); // intersect the line segment with each side of the polygon for (int i = 1; i < polygon.length; i++) { double[] intersection = GeometryUtils.intersectLineSegments(x1, y1, x2, y2, polygon[i - 1][0], polygon[i - 1][1], polygon[i][0], polygon[i][1]); if (intersection != null) { intersectionList.add(intersection); }//from w w w. j av a 2s . c o m } if (intersectionList.isEmpty()) { return null; } // order the intersection points by increasing distance from the start point java.util.Collections.sort(intersectionList, new DistComp()); // copy the coordinates of the intersection points double[][] intersections = new double[intersectionList.size()][2]; for (int i = 0; i < intersections.length; ++i) { final double[] inter = (double[]) intersectionList.get(i); intersections[i][0] = inter[0]; intersections[i][1] = inter[1]; } return intersections; } public static double[] intersectLineSegments(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { final double denominator = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); if (denominator == 0.d) { return null; // lines are parallel } final double ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denominator; if (ua <= 0.d || ua >= 1.d) { return null; // no intersection } final double ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denominator; if (ub <= 0.d || ub >= 1.d) { return null; // no intersection } return new double[] { x1 + ua * (x2 - x1), y1 + ua * (y2 - y1), ua }; } }