如何获取图片框中两点之间的鼠标坐标



谁能帮我解决这个问题?

我有一个带有图像的图片框,这个图像有一些坐标。 我的 X 从 60 开始,到 135 结束 我的 Y 统计数据为 75,结束于 120

因为我只有第一个和最后一个点,所以我想在将鼠标悬停在图像上时计算并查看坐标。

我从解决我的第一个问题开始:我必须界定我的开始和结束。 所以我尝试了一个跟踪栏。

我尝试首先获取当前的 X 位置:

将我的图片框设置为位置 x = 0;

将我的跟踪栏设置为位置 x = -10,所以我的第一个引脚将位于位置 0;

设置我的跟踪栏大小.x = picturebox.x + 20,所以我的最后一个图钉将位于图片框的末尾。

我的跟踪栏具有当前属性: 最小值 = 60,最大值 = 135;

在我的图片框中设置鼠标移动事件:

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
double dblValue;
dblValue = ((double)e.X/ (double)trackBar1.Width) * (trackBar1.Maximum - trackBar1.Minimum);
dblValue = dblValue + 60;
trackBar1.Value = Convert.ToInt32(dblValue);
lblX.Text = dblValue.ToString();
}

它几乎可以工作,但仍然不是很准确。 有人有一些可能奏效的想法吗?

我不完全确定您要做什么,但是如果您尝试获取图片框中的坐标,则 pictureBox 类上有一个名为PointToClient(Point)的函数,该函数将指定屏幕点的位置计算为客户端坐标。 可以使用MouseEventArgs中的 X 和 Y 坐标来创建要传递给函数的Point对象。

澄清一下:

MouseMove事件中MouseEventArgsXY属性是屏幕坐标 (0,0) 是屏幕的左上角。

许多控件(如PictureBox控件)都包含一个PointToClient方法,该方法将屏幕坐标转换为本地控件的坐标,其中 (0,0) 将是控件的左上角。

因此,例如,如果您的控件放置在屏幕上的位置 (60, 75) 并且右下角坐标为 (135, 120)。 如果鼠标位于控件上,并且距离左侧 10 像素,距离顶部 20 像素,则 MouseMove 事件中 MouseEventArgs 的XY属性将为:X= 70 和Y= 95。 如果使用PointToClient将这些坐标转换为图片框控件的内部坐标,它将指示X= 10 和Y= 20。

现在,如果您想要一个显示鼠标 X 坐标在某个控件上位置的相对指示的TrackBar,则可以按如下方式计算它:

// Set the minimum and maximum of the trackbar to 0 and 100 for a simple percentage.
trackBar1.Minimum = 0;
trackBar1.Maximum = 100;
// In the pictureBox1_MouseMove event have the following code:
trackBar1.Value = pictureBox1.PointToClient(new Point(e.X, e.Y)).X * 100 / pictureBox1.Width;

如果要让跟踪栏使用屏幕坐标来跟踪鼠标 X 坐标在某个控件上的相对位置,则应按如下方式计算:

// Set the minimum and maximum values of the track bar to the screen coordinates of the 
// control we want to track.
trackBar1.Minimum = pictureBox1.PointToScreen(0,0).X;
trackBar1.Maximum = pictureBox1.PointToScreen(pictureBox1.Width, 0).X;
// In the pictureBox1_MouseMove event have the following code:
trackBar1.Value = e.X;

如果要让跟踪栏使用某个控件的内部坐标来跟踪鼠标在该控件上的 X 坐标的内部位置,则应按如下方式计算它:

// Set the minimum and maximum values of the track bar to zero and the width of the
// control we want to track.
trackBar1.Minimum = 0;
trackBar1.Maximum = pictureBox1.Width;
// In the pictureBox1_MouseMove event have the following code:
trackBar1.Value = pictureBox1.PointToClient(new Point(e.X, e.Y)).X;
// or - not recommended - read below.
trackBar1.Value = e.X - pictureBox1.Left;

现在,有一个警告,那就是如果将控件放在其他控件中,例如面板内的面板等,则另一个控件内的控件的"世界"坐标基于它们在父控件中的位置。 这就是为什么通过PointToClient使用控件的内部坐标和通过PointToScreen使用内部坐标的屏幕坐标是一个好主意,否则您将不得不通过所有容器向上工作,直到到达屏幕,全程跟踪TopLeft坐标。

我希望这能回答你的问题。

最新更新