简体   繁体   中英

Resize PictureBox width and keep aspect ratio

I'm loading the image dynamically to a pre-existing PictureBox person_img that has all default values and is not sized correctly. I'm expecting to be able to do the sizing dynamically so that all images are 1/3 of people_popup_tab width.

I've tried many ways, including answers from similar questions. My last attempt was to load the image and set the SizeMode to AutoSize so that it would first get rendered at its full size, then I'd be able to get its width and height this way. Then I would use this width and height to know how to proportionately scale the image down.

But the image still renders all wonky. Some also simply don't show up now.

在此处输入图片说明

How can I resize the image to 1/3 of people_popup_tab width without losing aspect ratio?

My current code:

person_img.SizeMode = PictureBoxSizeMode.AutoSize;
person_img.Load(thisFaculty.imagePath);
int oldWidth = person_img.Width; 
int oldHeight = person_img.Height;
int newWidth = people_popup_tab.Width / 3;
int newHeight = oldHeight * (newWidth / oldWidth);
person_img.SizeMode = PictureBoxSizeMode.StretchImage;
person_img.Width = newWidth;
person_img.Height = newHeight;

First load the image to Bitmap class, than resize your picture box using the real dimensions of the image. Similar to below code

var bmp = new Bitmap(imageFile);
pictureBox1.Width = bmp.Width / 3;
pictureBox1.Height = bmp.Height / 3;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Image = bmp;

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