从PictureBox中的鼠标位置获取真实图像坐标

5
在我的 Windows 表单中,我有一个 PictureBox,它的图片是从一个目录加载的。
我需要在 PictureBox 中显示真实尺寸的图像,例如图像(宽度=1024,高度=768),而 PictureBox 的尺寸为(宽度=800,高度=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);
}     

你想将picture box设置为图像像素吗?还是你想在picture box中任意指向的位置显示像素? - Muhammad Saqlain
我想在picturebox中指向任何值与加载的真实图像中指向任何值相同的位置显示像素。 - Totzki3
1
顺便说一句:没有必要这样做 MouseEventArgs me = (MouseEventArgs)e; 因为 e 已经和 me 相同类型。 - Sammy
1个回答

6

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));
}

1
@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) ); - ASh
需要创建一个新的位图吗?你不能只使用Image属性的大小(PictureBox1.Image.Height)吗? - pinkfloydx33
@pinkfloydx33,我赞同你的观点。我本来想修复它(Bitmap b = (Bitmap)PictureBox1.Image;),但在处理过程中忘记了。实际上,你的建议更好,谢谢。 - ASh
@ASh 非常感谢,它运行得非常好,Bitmap b = new Bitmap(PictureBox1.Image); MessageBox.Show("X=" + (b.Width * me.X / PictureBox1.Width) + ", Y=" + (b.Height * me.Y / PictureBox1.Height) ); - Totzki3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接