【C#】求点到线段的垂线距离

 public float DistanceForPointToABLine(float x, float y, float x1, float y1, float x2, float y2)//所在点到AB线段的垂线长度
    {
        float reVal = 0f;
        bool retData = false;

        float cross = (x2 - x1) * (x - x1) + (y2 - y1) * (y - y1);
        if (cross <= 0)
        {
            reVal = (float)Math.Sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1));
            retData = true;
        }

        float d2 = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
        if (cross >= d2)
        {
            reVal = (float)Math.Sqrt((x - x2) * (x - x2) + (y - y2) * (y - y2));
            retData = true;
        }

        if (!retData)
        {
            float r = cross / d2;
            float px = x1 + (x2 - x1) * r;
            float py = y1 + (y2 - y1) * r;
            reVal = (float)Math.Sqrt((x - px) * (x - px) + (py - y) * (py - y));
        }

        return reVal;

    }

你可能感兴趣的:(【C#】算法)