简体   繁体   中英

C#: Resize picturebox to fit image

In my app (winforms), I'd like to load in different images. These images have different sizes, and different aspect ratios (let's say I have a 400x400, and a 1920x1200.) Now I have a picturebox to put these images in, and the picturebox's SizeMode property is set to Zoom .

Now I have an image in a picturebox, that is resized to fit within the picuterbox's boundaries. But if the picturebox has a different aspect ratio than the image has, I will be left with some unwanted empty space. Setting the SizeMode to stretch, is not an option.

?: So I'd like to know, if there is a way to get the size of the auto-resized image, so I can change the size of the picturebox accordingly.

Image myImg = new Image.FromFile(..//landscape.jpg)
int getWidth = myImg.Width;
int getHeight = myImg.Height;
// This does not work, as it gets the original size of the image (eg: in case of a 1920x1200, it gets 1920 and 1200 respectively)

This is what happens right now:

比率错误比率错误

This is what I'd like to have:

所需比例 Because the app should be able to process any image, I need to set these values dynamically, so no values can be preset.

Let us say the box is 400x400. When a picture goes into the box, it is resized to fit within the boxes boundaries but keeps it's aspect ratio. So what we need to do is calculate the new size of the image within the box, and resize the box to match.

Image myImg = new Image.FromFile(..//landscape.jpg)
int getWidth = myImg.Width;
int getHeight = myImg.Height;
double ratio = 0;
if(getWidth>getHeight)
{
    ratio = getWidth/400;
    getWidth=400;
    getHeight=(int)(getHeight/ratio);
}
else
{
    ratio = getHeight/400;
    getHeight=400;
    getWidth=(int)(getWidth/ratio);
}
pictureBox.Width=getWidth;
pictureBox.Height=getHeight;

(Don't know the exact classes so might throw an error or two, concept is sound though)

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