Search code examples
c#pictureboxcoordinate-transformation

C# WindowsForms PictureBox: Transformation between control coordinates and pixel position in image


I have a control with a PictureBox within it. The PictureBox displays an image (in Zoom mode, at least in this particular case). I need to do two kinds of things:

  • Click with the mouse and find out which pixel of the image I hit
  • Draw a vertical line over the PictureBox at a given column in the image.

Obviously, I need some kind of coordinate transformations between the control coordinates and the (row, column) of the pixel in the image. The first one I may have found (www.codeproject.com/Articles/20923/Mouse-Position-over-Image-in-a-PictureBox), but not the vice versa. Any ideas?


Solution

  • I can suggest a "workaround": you do not draw lines etc. on the PictureBox, but, instead, on the bitmap itself, using its Graphics. Then you can only use the image coordinates (row, column) and do not need to convert from control to image. The other way round (from mouse click to row and column), as you mention, is solved and can be used.