简体   繁体   中英

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

I want to assign height and width of dynamically created image to a canvas . Here is my code

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;

but it gives 0.0 value when i check in debug mode ,when I change image.Height to image.ActualHeight it gives NaN . How to resolve this.

You should use the ActualWidth and ActualHeight properties of the Image control. The Width and Height are the dimensions you want the control to have; by default their value is double.NaN , which means "Auto".

But anyway, it still won't be enough:

  • at this point, the image has not finished loading, so its width and height are not accessible yet. You need to initialize the image like that:

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

  • the Image control is not yet part of the visual tree, so its dimensions can't be computed

So ActualWidth and ActualHeight will still not give your the correct values... A better way would be to set the canvas size according to the width and height of the BitmapImage :

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

I solved it in this way

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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