计算平面上的二条线的交叉点

计算平面上的二条线的交叉点

public static int ccw(Point P0, Point P1, Point P2, bool PlusOneOnZeroDegrees)
{
int dx1, dx2, dy1, dy2;
dx1 = P1.X - P0.X; dy1 = P1.Y - P0.Y;
dx2 = P2.X - P0.X; dy2 = P2.Y - P0.Y;
if (dx1 * dy2 > dy1 * dx2) return +1;
if (dx1 * dy2 < dy1 * dx2) return -1;
if ((dx1 * dx2 < 0) || (dy1 * dy2 < 0)) return -1;
if ((dx1 * dx1 + dy1 * dy1) < (dx2 * dx2 + dy2 * dy2) && PlusOneOnZeroDegrees)
return +1;
return 0;
}
public static int ccw(double P0x, double P0y, double P1x, double P1y, double P2x, double P2y, bool PlusOneOnZeroDegrees)
{
double dx1, dx2, dy1, dy2;
dx1 = P1x - P0x; dy1 = P1y - P0y;
dx2 = P2x - P0x; dy2 = P2y - P0y;
if (dx1 * dy2 > dy1 * dx2) return +1;
if (dx1 * dy2 < dy1 * dx2) return -1;
if ((dx1 * dx2 < 0) || (dy1 * dy2 < 0)) return -1;
if ((dx1 * dx1 + dy1 * dy1) < (dx2 * dx2 + dy2 * dy2) && PlusOneOnZeroDegrees)
return +1;
return 0;
}

//是否相交

public static bool Intersect(Point P11, Point P12, Point P21, Point P22)
{
return ccw(P11, P12, P21, true) * ccw(P11, P12, P22, true) <= 0
&& ccw(P21, P22, P11, true) * ccw(P21, P22, P12, true) <= 0;
}

//交叉点

public static PointF IntersectionPoint(Point P11, Point P12, Point P21, Point P22)
{
double Kx = P11.X, Ky = P11.Y, Mx = P21.X, My = P21.Y;
double Lx = (P12.X - P11.X), Ly = (P12.Y - P11.Y), Nx = (P22.X - P21.X), Ny = (P22.Y - P21.Y);
double a = double.NaN, b = double.NaN;
if (Lx == 0)
{
if (Nx == 0)
throw new Exception("没有相交点!");
b = (Kx - Mx) / Nx;
}
else if (Ly == 0)
{
if (Ny == 0)
throw new Exception("没有相交点!");
b = (Ky - My) / Ny;
}
else if (Nx == 0)
{
if (Lx == 0)
throw new Exception("没有相交点!");
a = (Mx - Kx) / Lx;
}
else if (Ny == 0)
{
if (Ly == 0)
throw new Exception("没有相交点!");
a = (My - Ky) / Ly;
}
else
{
b = (Ky + Mx * Ly / Lx - Kx * Ly / Lx - My) / (Ny - Nx * Ly / Lx);
}
if (!double.IsNaN(a))
{
return new PointF((float)(Kx + a * Lx), (float)(Ky + a * Ly));
}
if (!double.IsNaN(b))
{
return new PointF((float)(Mx + b * Nx), (float)(My + b * Ny));
}
throw new Exception("计算相交点出错");
}

你可能感兴趣的:(计算)