开发者

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

Let's suppose I've got an image whic开发者_如何学运维h 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.


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();
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜