CSharp examples for System:Math Geometry
Intersection Of Two Lines
using System.Drawing; using System;//w w w .j av a2 s.c om public class Main{ public static bool IntersectionOfTwoLines(Point a, Point b, Point c, Point d, ref Point intersect) { double r, s; double denominator = (b.X - a.X) * (d.Y - c.Y) - (b.Y - a.Y) * (d.X - c.X); // If the denominator in above is zero, AB & CD are colinear if (denominator == 0) return false; double numeratorR = (a.Y - c.Y) * (d.X - c.X) - (a.X - c.X) * (d.Y - c.Y); // If the numerator above is also zero, AB & CD are collinear. // If they are collinear, then the segments may be projected to the x- // or y-axis, and overlap of the projected intervals checked. r = numeratorR / denominator; double numeratorS = (a.Y - c.Y) * (b.X - a.X) - (a.X - c.X) * (b.Y - a.Y); s = numeratorS / denominator; // If 0<=r<=1 & 0<=s<=1, intersection exists // r<0 or r>1 or s<0 or s>1 line segments do not intersect if (r < 0 || r > 1 || s < 0 || s > 1) return false; ///* // Note: // If the intersection point of the 2 lines are needed (lines in this // context mean infinite lines) regardless whether the two line // segments intersect, then // // If r>1, P is located on extension of AB // If r<0, P is located on extension of BA // If s>1, P is located on extension of CD // If s<0, P is located on extension of DC //*/ // Find intersection point intersect.X = (int)(a.X + (r * (b.X - a.X))); intersect.Y = (int)(a.Y + (r * (b.Y - a.Y))); return true; } }