private Point intersection ( int x1 , int y1 , int x2 , int y2 , int x3 , int y3 , int x4 , int y4 ) { double dem = ( x1 - x2 ) * ( y3 - y4 ) - ( y1 - y2 ) * ( x3 - x4 ) ; // Solve the intersect point double xi = ( ( x1 * y2 - y1 * x2 ) * ( x3 - x4 ) - ( x1 - x2 ) * ( x3 * y4 - y3 * x4 ) ) / dem ; double yi = ( ( x1 * y2 - y1 * x2 ) * ( y3 - y4 ) - ( y1 - y2 ) * ( x3 * y4 - y3 * x4 ) ) / dem ; // Check the point isn't off the ends of the lines if ( ( x1 - xi ) * ( xi - x2 ) >= 0 && ( x3 - xi ) * ( xi - x4 ) >= 0 && ( y1 - yi ) * ( yi - y2 ) >= 0 && ( y3 - yi ) * ( yi - y4 ) >= 0 ) { return new Point ( ( int ) xi , ( int ) yi ) ; } return null ; }
Intersect two lines