WPF how to show an Image.Source (BitmapSource) pixel position?

梦想的初衷 提交于 2019-11-30 07:46:41

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

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();
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!