使用c#为画布分配动态创建图像的高度和宽度

本文关键字:图像 创建 高度 动态 布分配 分配 使用 | 更新日期: 2023-09-27 18:07:43

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

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值,当我检查在调试模式,当我改变图像。图像的高度。它给出了NaN。如何解决这个问题

使用c#为画布分配动态创建图像的高度和宽度

您应该使用Image控件的ActualWidthActualHeight属性。WidthHeight是您希望控件具有的维度;默认值为double.NaN,即"Auto"。

但无论如何,这仍然不够:

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

    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;

我是这样解决的

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