问题
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.
回答1:
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
回答2:
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();
}
来源:https://stackoverflow.com/questions/1597681/wpf-how-to-show-an-image-source-bitmapsource-pixel-position