比较坐标时无法从 int 转换为 System.Drawing.Point



我想检查两组坐标是否彼此靠近。我看了一下这个答案,它建议使用毕达哥拉斯公式来计算两点之间的距离。

我正在比较的两组坐标是鼠标的当前位置,以及变量下的预设坐标point

if(Math.Sqrt(Math.Pow(point.X - this.PointToClient(Cursor.Position.X), 2) + Math.Pow(point.Y - this.PointToClient(Cursor.Position.Y), 2) < 50))
{
Console.WriteLine("Distance between the points is less than 50");
}

变量point具有点数据类型。

我使用this.PointToClient(Cursor.Position)而不是Cursor.Position因为我想获取相对于表单而不是相对于屏幕的坐标。但是使用它会给我以下错误:

无法从int转换为System.Drawing.Point

你把.X.Y放在错误的一边:首先转换点,然后取它的坐标。

另一个问题是< 50立场

if(Math.Sqrt(Math.Pow(point.X - this.PointToClient(Cursor.Position).X, 2) + 
Math.Pow(point.Y - this.PointToClient(Cursor.Position).Y, 2)) < 50)
{
Console.WriteLine("Distance between the points is less than 50");
}

您可能希望提取this.PointToClient(Cursor.Position)以使if更具可读性

var cursor = PointToClient(Cursor.Position); 
if(Math.Sqrt(Math.Pow(point.X - cursor.X, 2) + 
Math.Pow(point.Y - cursor.Y, 2)) < 50)
{
Console.WriteLine("Distance between the points is less than 50");
}

PointToClient期望一个Point,因为您的参数正在传递一个整数。所以改变这个

this.PointToClient(Cursor.Position.X)

自:

this.PointToClient(Cursor.Position).X

而且

this.PointToClient(Cursor.Position.Y)

this.PointToClient(Cursor.Position).Y

最新更新