How can I measure diagonal distance points?

偶尔善良 提交于 2019-11-30 04:37:37

问题


I can compute horizontal and vertical points, but I cant figure out how to compute distance using diagonal points. Can someone help me with this.

here's the code for my horizontal and vertical measuring:

private float ComputeDistance(float point1, float point2) 
{
        float sol1 = point1 - point2;
        float sol2 = (float)Math.Abs(Math.Sqrt(sol1 * sol1));

        return sol2;
}

protected override void OnMouseMove(MouseEventArgs e)
    {

        _endPoint.X = e.X;
        _endPoint.Y = e.Y;

        if (ComputeDistance(_startPoint.X, _endPoint.X) <= 10)
        {
            str = ComputeDistance(_startPoint.Y, _endPoint.Y).ToString();
        }
        else
        {
            if (ComputeDistance(_startPoint.Y, _endPoint.Y) <= 10)
            {
                str = ComputeDistance(_startPoint.X, _endPoint.X).ToString();
            }
        }
    }

Assuming that the _startPoint has been already set.

In this image the diagonal point is obviously wrong.


回答1:


You need to use Pythagoras' theorem.

d = Math.Sqrt(Math.Pow(end.x - start.x, 2) + Math.Pow(end.y - start.y, 2))



回答2:


I think you're looking for the Euclidean distance formula.

In mathematics, the Euclidean distance or Euclidean metric is the "ordinary" distance between two points that one would measure with a ruler, and is given by the Pythagorean formula.




回答3:


Well you might take a look at: http://en.wikipedia.org/wiki/Pythagorean_theorem




回答4:


Much time later... I'd like to add that you could use some built-in functionality of .NET:

using System.Windows;

Point p1 = new Point(x1, y1);
Point p2 = new Point(x2, y2);
Vector v = p1 - p2;
double distance = v.Length;

or simply:

static double Distance(double x1, double x2, double y1, double y2)
{
    return (new Point(x1, y1) - new Point(x2, y2)).Length;
}


来源:https://stackoverflow.com/questions/3819396/how-can-i-measure-diagonal-distance-points

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!