UWP:如何获取图片显示后的图片高宽 UI

UWP: How to get image height and width after the image is displayed on UI

我正在像这样从 IRandomAccessStream 加载图像:

    private async void SetImageSourceToImage(IRandomAccessStream stream)
    {
        var decoder = await BitmapDecoder.CreateAsync(stream);
        SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync();

        SoftwareBitmap softwareBitmapBGR8 = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);

        SoftwareBitmapSource bitmapSource = new SoftwareBitmapSource();
        await bitmapSource.SetBitmapAsync(softwareBitmapBGR8);

        myImage.Source = bitmapSource;
    }

这里是 XAML:

 <Grid Grid.Row="0" Background="AntiqueWhite">
            <Image x:Name="myImage" Stretch="Uniform"/>
            <InkCanvas x:Name="myInkCanvas"/>
            <InkToolbar x:Name="inkToolbar" VerticalAlignment="Bottom" HorizontalAlignment="Center"
          TargetInkCanvas="{x:Bind myInkCanvas}" />
        </Grid>

图像显示在屏幕上后,我想获取其 HeightWidth 以设置 InkCanvas 的高度和宽度。

问题是图像显示在屏幕上后,myImage 的 ActualWidth、ActualHeight、Height 和 Width 属性为 0 或 NaN。

确实有decoder.PixelWidthdecoder.PixelHeight两个值,但是不知道有没有用,因为我在XAML里面用的是Stretch="Uniform"

正如Justin所说,我们可以在Image的ImageOpened事件中得到实际的宽高值。

You can check ActualHeight and ActualWidth at run time after the image renders to get the measurement information. Or, you can handle ImageOpened and check image file properties such as PixelHeight and PixelWidth immediately before the image renders.

更多信息,请参考Image Class

当我添加 Image.ImageOpened 事件时,当我在 SetImageSourceToImage 方法中通过 Image.Source 设置源时,它似乎没有被触发。

我们可以在Image.Source中设置BitmapImage,即我们可以添加BitmapImageBitmapImage.ImageOpened事件。当BitmapImage源设置没有失败时出现。

例如:

<Image x:Name="myImage" Stretch="Uniform">
    <Image.Source>
        <BitmapImage x:Name="imageSource" ImageOpened="imageSource_ImageOpened" />
    </Image.Source>
</Image>

后面的代码:

private void imageSource_ImageOpened(object sender, RoutedEventArgs e)
{
    Debug.WriteLine(myImage.ActualHeight);
    Debug.WriteLine(myImage.ActualWidth);
}