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

标签 c# int point

我想检查两组坐标是否彼此接近。我看了看 this answer ,建议使用毕达哥拉斯公式计算两点之间的距离。

我比较的两组坐标是鼠标当前位置,和变量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 因为我想获取相对于表单的坐标,而不是相对于屏幕。但是使用它会给我以下错误:

Cannot convert from int to 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");
}

关于c# - 比较坐标时无法从 int 转换为 System.Drawing.Point,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59321793/

相关文章:

c - 在 C 中使用 Short 是一种不好的做法吗

java - 使用整数表示货币

java - 区域外的点最接近区域内的点?

ios - 核心图-iOS触摸事件很难在图形上选择点

c# - 在 Caliburn Micro 中的 ViewModel 之间切换

c# - iTextSharp pdf 中缺少 Font Awesome 图标

c# - 为什么我应该更喜欢单个 'await Task.WhenAll' 而不是多个等待?

c# - 流利的断言 : string does not contain a definition for ShouldBeEquivalentTo

c# - 如何强制 c# binary int 除法返回 double?

c# - 扩展结构的最简单方法(PointF)