对于PixelWidth和PixelHeight,BitmapImage返回0

Ant*_*ond 7 .net c# bitmapimage windows-runtime winrt-xaml

我正在尝试做一个非常简单的事情:获取图像的大小.

所以我创建了我,BitmapImage但是当我尝试访问PixelWidth和时,我得到0 PixelHeight.

我怎么能做到这一点呢?

编辑:(添加示例代码)

我只是这样做:

var baseUri = new Uri("ms-appx:///");
var bitmapImage = new BitmapImage(new Uri(baseUri, "Assets/Logo.png"));

MyImage.Source = bitmapImage;

Debug.WriteLine("Width: " + bitmapImage.PixelWidth + " Height: " + bitmapImage.PixelHeight);
Run Code Online (Sandbox Code Playgroud)

在控制台中,我得到:

Width: 0 Height: 0
Run Code Online (Sandbox Code Playgroud)

Pao*_*tti 5

当您想在为您的 设置源后使用图像属性时BitmapImage,您通常必须编写一个将在 上执行的事件处理程序ImageOpened

还要记住,ImageOpened只有在下载和解码图像(即使用Image.Source)时才会触发。

var bitmapImage = new BitmapImage(uri);
bitmapImage.ImageOpened += (sender, e) => 
{
    Debug.WriteLine("Width: {0}, Height: {1}",
        bitmapImage.PixelWidth, bitmapImage.PixelHeight);
};
image.Source = bitmapImage;
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法强制下载图像(不设置 image.source)? (4认同)