Here you can find the source of intersection(Line2D a, Line2D b)
Parameter | Description |
---|---|
x1 | Point 1 of Line 1 |
y1 | Point 1 of Line 1 |
x2 | Point 2 of Line 1 |
y2 | Point 2 of Line 1 |
x3 | Point 1 of Line 2 |
y3 | Point 1 of Line 2 |
x4 | Point 2 of Line 2 |
y4 | Point 2 of Line 2 |
public static Point2D intersection(Line2D a, Line2D b)
//package com.java2s; /**//from w w w .ja va2s .c om * Computes the intersection between two lines. The calculated point is approximate, * since integers are used. If you need a more precise result, use doubles * everywhere. * (c) 2007 Alexander Hristov. Use Freely (LGPL license). http://www.ahristov.com * * @param x1 Point 1 of Line 1 * @param y1 Point 1 of Line 1 * @param x2 Point 2 of Line 1 * @param y2 Point 2 of Line 1 * @param x3 Point 1 of Line 2 * @param y3 Point 1 of Line 2 * @param x4 Point 2 of Line 2 * @param y4 Point 2 of Line 2 * @return Point where the segments intersect, or null if they don't */ import java.awt.geom.Line2D; import java.awt.geom.Point2D; public class Main { /** * Computes the intersection between two lines. The calculated point is approximate, * since integers are used. If you need a more precise result, use doubles * everywhere. * (c) 2007 Alexander Hristov. Use Freely (LGPL license). http://www.ahristov.com * * @param x1 Point 1 of Line 1 * @param y1 Point 1 of Line 1 * @param x2 Point 2 of Line 1 * @param y2 Point 2 of Line 1 * @param x3 Point 1 of Line 2 * @param y3 Point 1 of Line 2 * @param x4 Point 2 of Line 2 * @param y4 Point 2 of Line 2 * @return Point where the segments intersect, or null if they don't */ public static Point2D intersection(Line2D a, Line2D b) { double x1 = a.getX1(), y1 = a.getY1(), x2 = a.getX2(), y2 = a.getY2(), x3 = b.getX1(), y3 = b.getY1(), x4 = b.getX2(), y4 = b.getY2(); double d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); if (d == 0) { return null; } double xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; double yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; return new Point2D.Double(xi, yi); } }