1、二维点:
public class XPoint
{
public double X { get; set; }
public double Y { get; set; }
public XPoint()
{
X = double.NaN;
Y = double.NaN;
}
public XPoint(double x, double y)
{
X = x;
Y = y;
}
/// <summary>
/// 两点之间的距离
/// </summary>
/// <param name="p1"></param>
/// <param name="p2"></param>
/// <returns></returns>
public static double Distance(XPoint p1, XPoint p2)
{
return Math.Sqrt((p2.X - p1.X) * (p2.X - p1.X) + (p2.Y - p1.Y) * (p2.Y - p1.Y));
}
/// <summary>
/// 判断点坐标中是否包含无效值
/// </summary>
/// <param name="pnt"></param>
/// <returns></returns>
public static bool IsNaN(XPoint pnt)
{
if (double.IsNaN(pnt.X) || double.IsNaN(pnt.Y))
{
return true;
}
return false;
}
/// <summary>
/// 判断四个点是否构成一个矩形(适当放宽矩形的精度控制,已提高适应性)
/// </summary>
/// <param name="p1"></param>
/// <param name="p2"></param>
/// <param name="p3"></param>
/// <param name="p4"></param>
/// <param name="tol">精度</param>
/// <returns></returns>
public static bool JugeRect(XPoint p1, XPoint p2, XPoint p3, XPoint p4, double tol = 0.001)
{
double xy = Math.Max(Math.Abs(p3.X - p1.X), Math.Abs(p3.Y - p1.Y));
bool flag1 = Math.Abs(p1.Y - p2.Y) < tol * 10 * xy;
bool flag2 = Math.Abs(p3.Y - p4.Y) < tol * 10 * xy;
bool flag3 = Math.Abs(p1.X - p4.X) < tol * 10 * xy;
bool flag4 = Math.Abs(p2.X - p3.X) < tol * 10 * xy;
return flag1 && flag2 && flag3 && flag4;
}
}
2、二维线段:
public class XLine
{
public XPoint StartPt { get; set; }
public XPoint EndPt { get; set; }
/// <summary>
/// 线段由多段构成时,去掉中间的空隙,剩余部分相对于起点距离比例的闭区间
/// </summary>
public XRangeList Range { get; set; }
public XLine(XPoint start, XPoint end)
{
StartPt = start;
EndPt = end;
Range = new XRangeList();
Range.Merge(new XRange(0, 1));
}
/// <summary>
/// 线段长度
/// </summary>
/// <returns></returns>
public double Length()
{
//勾股定理
return Math.Sqrt((this.EndPt.X - this.StartPt.X) * (this.EndPt.X - this.StartPt.X) + (this.EndPt.Y - this.StartPt.Y) * (this.EndPt.Y - this.StartPt.Y));
}
/// <summary>
/// 判断点是否在线段有效区间内
/// </summary>
/// <param name="pnt"></param>
/// <returns></returns>
public bool In(XPoint pnt)
{
double dx = this.EndPt.X - this.StartPt.X;
double dy = this.EndPt.Y - this.StartPt.Y;
if (Math.Abs(dx) > Math.Abs(dy))
{
double v = (pnt.X - th