【问题标题】:Assign height and width of dynamically created image to canvas using c#使用 c# 将动态创建的图像的高度和宽度分配给画布
【发布时间】:2026-01-20 21:25:01
【问题描述】:

我想将动态创建的图像的高度和宽度分配给画布。 这是我的代码

Image image=new Image();
BitmapImage bm=new BitmapImage();
bm.UriSource=new Uri("url",Urikind.RelativeOrAbsolute);
image.Source=bm;
MyCanvas.Height=image.Height;
MyCanvas.Width=image.Width;

但是当我在调试模式下检查时它给出 0.0 值,当我将 image.Height 更改为 image.ActualHeight 时它给出 NaN。 如何解决这个问题。

【问题讨论】:

    标签: c# winrt-xaml windows-8.1


    【解决方案1】:

    您应该使用Image 控件的ActualWidthActualHeight 属性。 WidthHeight 是您希望控件具有的尺寸;默认情况下,它们的值为double.NaN,表示“自动”。

    但无论如何,还是不够:

    • 此时,图像还没有完成加载,所以它的宽度和高度还不能访问。您需要像这样初始化图像:

      BitmapImage bm=new BitmapImage(); bm.BeginInit(); bm.UriSource=new Uri("url",Urikind.RelativeOrAbsolute); bm.EndInit();

    • Image 控件还不是可视化树的一部分,因此无法计算其尺寸

    所以ActualWidthActualHeight 仍然不会给你正确的值...更好的方法是根据BitmapImage 的宽度和高度设置画布大小:

    MyCanvas.Height= bm.Height;
    MyCanvas.Width = bm.Width;
    

    【讨论】:

    • @user3355043,对不起,我没有意识到它是一个 WinRT 应用程序......我的答案适用于 WPF,而不是 WinRT。忘记 BeginInit/EndInit 方法,它们在 WinRT 中不存在。尝试改用 PixelWidth 和 PixelHeight
    【解决方案2】:

    我是这样解决的

    BitmapImage bm = new BitmapImage();
     bm.UriSource=new Uri("ms-appx:///" + d.source, UriKind.RelativeOrAbsolute);
     bm.ImageOpened += (sender, e1) =>
      {
       DrawCanvas.Height = bm.PixelHeight;
       DrawCanvas.Width = bm.PixelWidth;
       };
    

    【讨论】: