当比较坐标时,无法将int转换为System.Drawing.Point。

3
我想检查两组坐标是否相近。我看过这个答案,它建议使用勾股定理计算两点之间的距离。
我要比较的两组坐标是鼠标当前位置和变量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具有点(point)数据类型。
我正在使用this.PointToClient(Cursor.Position)而不是Cursor.Position,因为我想获取相对于窗体的坐标,而不是相对于屏幕。然而,使用此方法会出现以下错误:

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

2个回答

4

您已经将.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");
}

我遇到了这个错误:无法将布尔值转换为双精度浮点数 - The Codesee
@The Codesee:我明白了,<50也放错位置了,请看我的修改。 - Dmitry Bychenko

0

PointToClient 期望传入一个 Point 类型的参数,但你却传入了一个 int。请进行更改。

this.PointToClient(Cursor.Position.X)

到:

this.PointToClient(Cursor.Position).X

还有

this.PointToClient(Cursor.Position.Y)

this.PointToClient(Cursor.Position).Y

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接