private void btnShortLen_Click(object sender, EventArgs e) { System.Diagnostics.Stopwatch sw0 = new System.Diagnostics.Stopwatch(); sw0.Start(); int i = 0; while (i < 100000) { Point pi1 = new Point(0, 0); Point pst = new Point(0, 4); Point ped = new Point(4, 0); double dis = GetMinDistance(pst, ped, pi1); i++; } sw0.Stop(); var s0 = sw0.ElapsedMilliseconds; //4 此方法省时 System.Diagnostics.Stopwatch sw1 = new System.Diagnostics.Stopwatch(); sw1.Start(); i = 0; while (i < 100000) { Vector3 point_a = new Vector3(0f, 0f, 1.0f); Vector3 point_b = new Vector3(0f, 4.0f, 1.0f); Vector3 point_c = new Vector3(4f, 0f, 1.0f); VectorCalculate vec_Calculate = new VectorCalculate(point_b, point_c, point_a); float res = vec_Calculate.DistanceCalculate(); i++; } sw1.Stop(); var s1 = sw1.ElapsedMilliseconds; //10 } /****点到直线的距离*** c#版本 * 过点(x1,y1)和点(x2,y2)的直线方程为:KX -Y + (x2y1 - x1y2)/(x2-x1) = 0 * 设直线斜率为K = (y2-y1)/(x2-x1),C=(x2y1 - x1y2)/(x2-x1) * 点P(x0,y0)到直线AX + BY +C =0DE 距离为:d=|Ax0 + By0 + C|/sqrt(A*A + B*B) * 点(x3,y3)到经过点(x1,y1)和点(x2,y2)的直线的最短距离为: * distance = |K*x3 - y3 + C|/sqrt(K*K + 1) */ public static double GetMinDistance(PointF pstart, PointF pend, PointF poxy) { double dis = 0; if (pstart.X == pend.X) { dis = Math.Abs(poxy.X - pstart.X); return dis; } double lineK = (pend.Y - pstart.Y) / (pend.X - pstart.X); double lineC = (pend.X * pstart.Y - pstart.X * pend.Y) / (pend.X - pstart.X); dis = Math.Abs(lineK * poxy.X - poxy.Y + lineC) / (Math.Sqrt(lineK * lineK + 1)); return dis; } } class VectorCalculate { public VectorCalculate(Vector3 point_a, Vector3 point_b, Vector3 point_c) { _point_a = point_a; _point_b = point_b; _point_c = point_c; } public float DistanceCalculate() { Vector3 vec_ab = _point_b - _point_a; Vector3 vec_ac = _point_c - _point_a; float distance = 0.0f; Vector3 vec_Normalize = Vector3.Normalize(vec_ab); float projection_length = Vector3.Dot(vec_ac, vec_Normalize); //计算出投影向量的模 Vector3 vec_Projection = Vector3.Multiply(projection_length, vec_Normalize); //计算出投影向量 distance = Vector3.Distance(vec_ac, vec_Projection); return distance; } private Vector3 _point_a; private Vector3 _point_b; private Vector3 _point_c; }
本文来自博客园,作者:董锡振,转载请注明原文链接:https://www.cnblogs.com/dongxizhen/p/17755558.html