Search code examples
c#wpfimagecanvasviewbox

Why Image size is NaN (wpf) and how to resize via mouse wheel?


I want to load an image and put it into a viewbox. The image is displayed correctly, but, when I'm going to get it's width and height, it's both NaN.

This is my image load code :

Image img = new Image();
img.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("1.png");

Viewbox vb = new Viewbox();

vb.Width = img.Width;
vb.Height = img.Height;

vb.Child = img;

cnv.Children.Add(vb);

The reason I want to get the image width and height is so I could resize it (via viewbox resize) later inside the application.

Any idea how to get the image dimension?

And this is how I'm going to resize it (via mouse wheel)

    private void cnv_MouseWheel(object sender, MouseWheelEventArgs e)
    {
        if (vb != null)
        {
            vb.Width += Mouse.MouseWheelDeltaForOneLine;
            vb.Height += Mouse.MouseWheelDeltaForOneLine;
        }
    }

And it returns error and said that vb.Width is not a valid value.

Questions to sum this up :

  1. How to get the image width / height in wpf?
  2. How to resize the viewbox (which will also result in image resize) via mouse wheel? For example, if I scroll up the wheel, the width and height is added by 1, and if I scroll down the wheel, the width and height is reduced by 1.

Thank you

P.S. Viewbox vb; and Image img; is a global variable, I just shorten the script down. P.S.S. I know if the Viewbox width and height initialized by a number, lets say 100 and 100, it will work, I just wanna know how to get the image original size.

EDIT : The resize can be achieved by detecting whether it's scrolled up or down by detecting e.Delta > 0 or e.Delta < 0 (Source : http://social.msdn.microsoft.com/Forums/vstudio/en-US/170c4fd0-1441-4d83-903d-594af75f8fb4/detect-mouse-scroll)


Solution

  • It seems as though the Image object is not fully loaded at that stage. I believe that you can use the Width and Height properties of the ImageSource class instead. That should be fully loaded at this stage.

    ImageSource.Width Property
    ImageSource.Height Property

    For other users, you can also possibly find the values that you want from the ActualWidth and ActualHeight properties of the Image class (inherited from the FrameworkElement class) instead of the more usual Width and Height properties.

    FrameworkElement.ActualHeight Property
    FrameworkElement.ActualWidth Property