【问题标题】:Get real image coordinates from mouse location in PictureBox从 PictureBox 中的鼠标位置获取真实图像坐标
【发布时间】:2017-03-03 18:40:04
【问题描述】:

在我的 Windows 窗体中,我有一个 PictureBox,它的图像是从目录加载的。

我需要将图片的真实尺寸显示到PictureBox中,例如图片(width=1024,height=768),picturebox(width=800,height=600)。

我想将图像加载到具有相同像素值的 PictureBox 中。这样当我指向 PictureBox 中的任何位置时,我得到的像素值与我指向真实图像时得到的像素值相同(例如使用 Photoshop 获取尺寸)。

目前尝试但没有成功:

private void PictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    MouseEventArgs me = (MouseEventArgs)e;
    Bitmap b = new Bitmap(PictureBox1.Image);
    MessageBox.Show("X=" + (1024/ 800) * me.X + ", Y=" + (768/ 600) *me.Y);
}     

【问题讨论】:

  • 您想将图片框设置为图像像素吗?或者您想在指向图片框中的任何位置时显示像素?
  • 我想在指向图片框中的任何位置时显示像素,其值与我在加载的真实图像中指向任何位置时的值相同
  • 顺便说一句:没有必要这样做 MouseEventArgs me = (MouseEventArgs)e; e 已经与 me 相同的类型

标签: c# winforms


【解决方案1】:

1024 / 800768 / 600 都是整数除法,产生1

改变操作顺序:

MessageBox.Show("X=" + (1024 * me.X / 800)  + ", Y=" + (768 * me.Y / 600));

这里是完整的方法(假设PictureBox1.SizeMode 设置为StretchImage)。使用真实的宽度和高度值,而不是“魔法”常量 1024x768 或 800x600

private void PictureBox1_MouseDown(object sender, MouseEventArgs me)
{            
    Image b = PictureBox1.Image;
    int x = b.Width * me.X / PictureBox1.Width;
    int y = b.Height * me.Y / PictureBox1.Height;
    MessageBox.Show(String.Format("X={0}, Y={1}", x, y));
}

【讨论】:

  • @user3405070,有什么改善吗?我假设PictureBox1.SizeMode 设置为 StretchImage。图像真的有 1024x768 的大小吗?在这样的公式中使用实际尺寸:Bitmap b = new Bitmap(PictureBox1.Image); MessageBox.Show("X=" + (b.Width * me.X / PictureBox1.Width) + ", Y=" + (b.Height * me.Y / PictureBox1.Height) );
  • 是否需要新建Bitmap?不能只使用 Image 属性 (PictureBox1.Image.Height) 的大小吗?
  • @pinkfloydx33,我同意你的看法。我正要修复它(Bitmap b = (Bitmap)PictureBox1.Image;)但在处理过程中忘记了。实际上,您的建议更好,谢谢
  • @ASh 非常感谢,效果很好,Bitmap b = new Bitmap(PictureBox1.Image); MessageBox.Show("X=" + (b.Width * me.X / PictureBox1.Width) + ", Y=" + (b.Height * me.Y / PictureBox1.Height) );
猜你喜欢
  • 1970-01-01
  • 2017-11-19
  • 1970-01-01
  • 2020-10-25
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
相关资源
最近更新 更多