2

I have a bitmap image (2000 x 2000) in a ContentPresenter attached to a ScrollViewer. So the image can be zoomed and scrolled.

Is there an easy way to know the x,y coordinates of the mouse in relation to the image? That is to say, as I pass the mouse over the image it returns the corresponding x,y of the pixel over which it passes?

Worse case scenario is to calculate the offset from the edge of the window and then multiply the x,y of the mouse by the scrolling and zooming factor.

I was just wondering if there was a method already built-in to WPF that would handle this.

zetar
  • 1,225
  • 2
  • 20
  • 45
  • http://msdn.microsoft.com/en-GB/library/system.windows.uielement.translatepoint.aspx – Kent Boogaart May 24 '13 at 14:37
  • That seems to translate the point in relation to the contentpresenter, but I don't think it will calculate zoom and pan. – zetar May 24 '13 at 15:00
  • Your "worst case scenario" is pretty much 1-2 lines of code. I doub't WPF has something for you. – Erti-Chris Eelmaa May 24 '13 at 16:06
  • I found the solution over here: [link](http://stackoverflow.com/questions/1597681/wpf-how-to-show-an-image-source-bitmapsource-pixel-position) – zetar May 24 '13 at 16:21

1 Answers1

1

This will calculate the 'zoomed' and 'panned' offset for the mouse over a bitmap in Contentviewer and scrollabar:

                ImageSource imageSource = image.Source;
            BitmapImage bitmapImage = (BitmapImage)imageSource;
             pixelMousePositionX = e.GetPosition(image).X * bitmapImage.PixelWidth / image.Width;
             pixelMousePositionY = e.GetPosition(image).Y * bitmapImage.PixelHeight / image.Height;
zetar
  • 1,225
  • 2
  • 20
  • 45
  • I had a better result with `var pixelMousePositionX = e.GetPosition(myImage).X * bitmapImage.PixelWidth / myImage.ActualWidth; var pixelMousePositionY = e.GetPosition(myImage).Y * bitmapImage.PixelHeight / myImage.ActualHeight;` – Arsen Zahray Jan 17 '17 at 18:59
  • Where did you get this formula? – g00n3r Sep 03 '20 at 19:18