且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将鼠标坐标转换为位图的坐标?

更新时间:2023-02-11 11:41:31

  private   void  pictureBox1_Click(  object  sender,EventArgs e)
{
Point topLeft = PointToScreen( new Point (pictureBox1.Left,pictureBox1.Top));
int x = MousePosition.X - topLeft.X;
int y = MousePosition.Y - topLeft.Y;

MessageBox.Show( string .Format( X {0} Y {1},x,y));
}





因此,请使用PointToScreen在屏幕内查找图片框的坐标。


问题在于:你提到位图坐标,并没有提到要点击的内容。如果我们假设这是点击 PictureBox ,则像素坐标与此控件的坐标完全相同。就这样。



(如果您的控件不同(但为什么?),您可以重新计算坐标平移投影屏幕坐标或考虑控件的位置。)



现在,使用 PictureBox 是值得怀疑的。它可能有用,也可能没有用,但通常不会:它会在没有任何帮助的情况下造成麻烦,只会占用额外的资源,甚至会花费更多的开发时间。请查看我过去的答案:

在其中附加图片图片框 [ ^ ],

画一个矩形C# [ ^ ],

如何从旧图纸中清除面板 [ ^ ]。



-SA

I have a picturebox,I could get the mouse's (x,y) from mouse double click event ,but how to conver the (x,y) to bitmap's real (x,y)?

private void pictureBox1_Click(object sender, EventArgs e)
{
  Point topLeft = PointToScreen(new Point(pictureBox1.Left, pictureBox1.Top));
  int x = MousePosition.X - topLeft.X;
  int y = MousePosition.Y - topLeft.Y;

  MessageBox.Show(string.Format("X{0} Y{1}", x, y));
}



So use PointToScreen to find the coordinates of the picturebox within the screen.


Here is the problem: you mention "bitmap coordinates", and don't mention what to click on. If we assume that this is a click on a PictureBox, the pixel coordinates are exactly the same as the coordinates of this control. That's all.

(If your control is different (but why?), you can re-calculate the coordinate translation throw screen coordinates or taking into account control's locations.)

Now, using PictureBox is questionable. It may or may not be useful, but usually not: it creates hassles without any help, only eats additional resources and even more of your development time to be spent for nothing. Please see my past answers:
Append a picture within picturebox[^],
draw a rectangle in C#[^],
How do I clear a panel from old drawing[^].

—SA