【问题标题】:WPF how to show an Image.Source (BitmapSource) pixel position?WPF如何显示一个Image.Source(BitmapSource)的像素位置?
【发布时间】:2009-10-20 22:27:24
【问题描述】:

假设我有一张以缩放方式显示其来源的图像,我该如何使用 MouseMove 事件在标签或文本块中显示光标所在的像素位置?

(我需要像素坐标而不是图像相对于其大小的坐标)

提前致谢。

【问题讨论】:

    标签: wpf coordinates pixel mousemove


    【解决方案1】:

    您可以从 ImageSource 中找出实际的像素高度和宽度。

        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;
    

    玩得开心

    Jobi Joy

    【讨论】:

    • 感谢您的帮助,您的解决方案似乎简单高效。非常感谢!
    • 最好使用mage.ActualWidth 而不是mage.Width
    【解决方案2】:

    如果您的图片的 XAML 如下:

     <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>
    

    可能Image控件的宽度是double.Nan,所以我们需要使用ActualWidth属性。所以代码如下:

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

    【讨论】:

    • 你是对的,上一个帖子的答案图像宽度返回 NaN
    • 我的号码很差。我有它 VAlignment=Top HAlignment=Center Stretch=Uniform。我在网格中有图像。你们有什么建议吗?
    猜你喜欢
    • 2010-12-16
    • 2010-10-01
    • 1970-01-01
    • 2012-05-05
    • 2019-12-15
    • 2014-09-14
    • 2012-02-28
    • 2011-03-11
    • 1970-01-01
    相关资源
    最近更新 更多