[英]Calculate distance between two mouse points
我需要计算鼠标在屏幕上单击的两个地方之间的距离。
鼠标移动事件(eX&eY)中填充了目标(x和Y)和源(X和Y)
我有distance = Math.Sqrt(Math.Pow(targetX - sourceX, 2) + Math.Pow(targetY - sourceY, 2));
这给了我一个结果,但如果我说实话,我不确定测量单位是什么或如何转换它。 如何将结果转换为有意义的结果,如cm或英寸? 我猜我需要考虑屏幕资源吗?
更新我只是真的消磨时间。 不寻找一个有效的解决方案。 它只会持续一两天。
这是MoveMove
事件和调用。 应该发布之前更清楚。
private void HookManager_MouseMove(object sender, MouseEventArgs e)
{
labelMousePosition.Text = string.Format("x={0:0000}; y={1:0000}", e.X, e.Y);
AddDistance(Convert.ToDouble(e.X), Convert.ToDouble(e.Y));
}
private void AddDistance(double targetX, double targetY)
{
if (sourceX != 0 && sourceY != 0)
{
double distance = Convert.ToDouble(lblDistanceTravelled.Text);
distance =+ Math.Sqrt(Math.Pow(targetX - sourceX, 2) + Math.Pow(targetY - sourceY, 2));
lblDistanceTravelled.Text = distance.ToString();
}
sourceX = targetX;
sourceY = targetY;
}
变量targetX和sourceX最有可能是像素,因此生成的距离将以像素为单位。
要将其转换为“屏幕上的英寸”,您必须知道屏幕的大小。 您可以确定每英寸的像素数并从那里进行转换(尽管这只能估算出如果实际将标尺固定在屏幕上会得到什么)。 要获得每英寸像素数,请参阅
从这个问题,你可以得到如下DPI(但阅读许多警告的接受答案)
PointF dpi = PointF.Empty;
using(Graphics g = this.CreateGraphics()){
dpi.X = g.DpiX;
dpi.Y = g.DpiY;
}
单位之间的转换如下:
lengthInInches = numberOfPixes / dotsPerInch
这里“点”和“像素”的含义相同。 我使用的是通用术语。
你可以通过获得“当前的DPI”
int currentDPI = 0;
using (Graphics g = this.CreateGraphics())
{
currentDPI = (int)g.DpiX;
}
然后你就可以得到
double distanceInInches = distance/*InPixels*/ / currentDPI;
但是,系统的DPI设置无法真正依赖于从像素距离到屏幕英寸距离的真正转换。
double dpc = this.CreateGraphics().DpiX / 2.54; //Dots Per Centimeter
//calculate the number of pixels in the line
double lineLengthInPixels = Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));
//line length in centimenters
double lineLengthInCentimeters = dpc / lineLengthInPixels;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.