繁体   English   中英

使用C#将动态创建的图像的高度和宽度分配给画布

[英]Assign height and width of dynamically created image to canvas using c#

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

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;

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

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

但是无论如何,这还不够:

  • 此时,图片尚未完成加载,因此尚无法访问其宽度和高度。 您需要像这样初始化图像:

    BitmapImage bm = new BitmapImage(); bm.BeginInit(); bm.UriSource =新的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;
   };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM