1

Let's suppose I've got an image which shows its source in a scaled way, how could i use a MouseMove event to show in a label or textblock the pixel position in which the cursor is?

(I need the pixel coordinates not the coordinates of the image relative to its size)

Thanks in advance.

Mario
  • 319
  • 5
  • 12

2 Answers2

7

You can find out the actual pixel height and width from the ImageSource.

    ImageSource imageSource = image.Source;
    BitmapImage bitmapImage = (BitmapImage) imageSource ;

Now since you got the image displayed in Image control. You can easily map the mouse position to the Pixel scale.

pixelMousePositionX = e.GetPosition(image).X * bitmapImage.PixelWidth/image.Width;
pixelMousePositionY = e.GetPosition(image).Y * bitmapImage.PixelHeight/image.Height;

Have fun

Jobi Joy

Jobi Joy
  • 49,102
  • 20
  • 108
  • 119
3

If your Image's XAML as follow:

 <Border Grid.Row="1" Grid.Column="0" 
            BorderThickness="3" 
            BorderBrush="BlueViolet">
        <Image x:Name="Image_Box" 
               VerticalAlignment="Stretch"
               HorizontalAlignment="Stretch"
               Source="8.jpg"
               Stretch="Uniform"
               MouseMove="ImageBox_OnMouseMove"
               />
    </Border>

Maybe the Image control's width is double.Nan ,So we need to use ActualWidth property. so the Code as follow:

private void ImageBox_OnMouseMove(object sender, MouseEventArgs e)
    {
        ImageSource imageSource = Image_Box.Source;
        BitmapSource bitmapImage = (BitmapSource)imageSource;
        TextBoxCursor_X.Text =( e.GetPosition(Image_Box).X * bitmapImage.PixelWidth / Image_Box.ActualWidth).ToString();
        TextBoxCursor_Y.Text = (e.GetPosition(Image_Box).Y * bitmapImage.PixelHeight / Image_Box.ActualHeight).ToString();
    }
huoxudong125
  • 1,966
  • 2
  • 26
  • 42
  • 1
    You're right, the previous answer to the post the Image width is returning NaN – Sweta Dwivedi Aug 17 '16 at 07:07
  • My numbers are way off. I have it VAlignment=Top HAlignment=Center Stretch=Uniform. I have the image inside a Grid. Do you guys suggest anything? – g00n3r Sep 03 '20 at 18:07