get Intersection - Java 2D Graphics

Java examples for 2D Graphics:Point

Description

get Intersection

Demo Code


//package com.java2s;
import java.awt.Point;

public class Main {
    public static Point getIntersection(int l1x1, int l1y1, int l1x2,
            int l1y2, int l2x1, int l2y1, int l2x2, int l2y2) {
        double d = (l2y2 - l2y1) * (l1x2 - l1x1) - (l2x2 - l2x1)
                * (l1y2 - l1y1);/* w w w  .  j a  va2s  .  c o m*/
        double na = (l2x2 - l2x1) * (l1y1 - l2y1) - (l2y2 - l2y1)
                * (l1x1 - l2x1);
        double nb = (l1x2 - l1x1) * (l1y1 - l2y1) - (l1y2 - l1y1)
                * (l1x1 - l2x1);
        if (d == 0D)
            return null;

        double ua = na / d;
        double ub = nb / d;
        if (ua >= 0D && ua <= 1D && ub >= 0D && ub <= 1D) {
            Point intersect = new Point();
            intersect.x = (int) (l1x1 + (ua * (l1x2 - l1x1)));
            intersect.y = (int) (l1y1 + (ua * (l1y2 - l1y1)));
            return intersect;
        }

        return null;
    }
}

Related Tutorials