Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get real image coordinates from mouse location in PictureBox

Tags:

c#

winforms

In my Windows form I have a PictureBox which image is loaded from a directory.

I need to display the real dimension of the image into the PictureBox, for example the image (width=1024,height=768), and the picturebox (width=800, height=600).

I want to load the image into the PictureBox with same pixel values. So that when I point anywhere in PictureBox I get the pixel value same with the pixel value that I get if I point to the real image (example get dimension using Photoshop).

Tried so far but no success:

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);
}     
like image 526
Totzki3 Avatar asked Mar 03 '17 08:03

Totzki3


1 Answers

1024 / 800 and 768 / 600 are both integer division which produce 1

change order of operations:

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

Here is complete method (assuming PictureBox1.SizeMode is set to StretchImage). Use real width and height values, not "magic" constants 1024x768 or 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));
}
like image 198
ASh Avatar answered Sep 22 '22 18:09

ASh