Get intersecting point of two lines - Java java.lang

Java examples for java.lang:Math Geometry Line

Description

Get intersecting point of two lines

Demo Code


//package com.java2s;

import java.awt.geom.Line2D;

import java.awt.geom.Point2D;

public class Main {
    /**/*ww w . j  av a 2  s .co  m*/
     * Get intersecting point of two lines
     * 
     * @param line1
     * @param line2
     * @return Point2D the intersecting point
     */
    public static Point2D getIntersection(final Line2D line1,
            final Line2D line2) {

        double x1, y1, x2, y2, x3, y3, x4, y4;
        x1 = line1.getX1();
        y1 = line1.getY1();
        x2 = line1.getX2();
        y2 = line1.getY2();
        x3 = line2.getX1();
        y3 = line2.getY1();
        x4 = line2.getX2();
        y4 = line2.getY2();
        double x = ((x2 - x1) * (x3 * y4 - x4 * y3) - (x4 - x3)
                * (x1 * y2 - x2 * y1))
                / ((x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4));
        double y = ((y3 - y4) * (x1 * y2 - x2 * y1) - (y1 - y2)
                * (x3 * y4 - x4 * y3))
                / ((x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4));

        return new Point2D.Double(x, y);

    }
}

Related Tutorials