Domanda

I am wondering if it is possible to get the displayed image dimensions of an image that has been re-sized to fit a PictureBox.

The PictureBox's SizeMode property is set to Zoom. So the aspect ration of the original Image is preserved. I need to get the displayed Image size however, which is not publicly available through the API.

I have read some answers that included reflection, but I would rather not do this.

È stato utile?

Soluzione

Easiest way is to just grab the aspect ratio yourself it's simple math after all.

First determine the if the image is vertical or horizontal then simply grab the picturebox height or width (respectively) and determine the width or height (respectively) of the original image's aspect ratio given that value.

OriginalImg.Height / OriginalImage.Width x PictureBox.Width = PictureBox.Height

Altri suggerimenti

This function does what you want to do:

private Size GetDisplayedImageSize(PictureBox pictureBox)
{
    Size containerSize = pictureBox.ClientSize;
    float containerAspectRatio = (float)containerSize.Height / (float)containerSize.Width;
    Size originalImageSize = pictureBox.Image.Size;
    float imageAspectRatio = (float)originalImageSize.Height / (float)originalImageSize.Width;

    Size result = new Size();
    if (containerAspectRatio > imageAspectRatio)
    {
        result.Width = containerSize.Width;
        result.Height = (int)(imageAspectRatio * (float)containerSize.Width);
    }
    else
    {
        result.Height = containerSize.Height;
        result.Width = (int)((1.0f / imageAspectRatio) * (float)containerSize.Height);
    }
    return result;
}

Do you have to use PictureBox inevitably? I found a thread where they give some options to solve your problem. It seems kind of dirty though...

1) Set the PictureBox to Normal or Center Image, and do the Image re-sizing yourself (using the Form Resize event), Taking care of all the math here is a little complicated, but very doable...(See the Crop/Zoom thread NOTE: that is VB6 Code, but the math is the same)

2) Just use the math and calculate the positions... Again the math is a little more complicated but also doable.. (see same thread as above for the math)..

I suppose it is a WinForms application. Or could you use WPF controls as well?

In WPF you could get the dimensions through ActualWidth and ActualHeight.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top