Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Picturebox Bitmap Scaling

Tags:

c#

winforms

I have a Picturebox and a ton of Bitmaps that can be displayed in it. The relative size of the Bitmap when compared to the others is of importance to the user. They need to be able to see that one image is smaller or bigger than another. The Bitmap must also fit in the picturebox entirely and the picturebox cannot be resized.

When simply displaying the Bitmaps unscaled in a huge picturebox the relative sizes of the bitmaps is easy to see, but when trying to fit them in a small box and having to scale them down my problem starts.

When using the Stretch PictureBoxSizeMode as you would imagine the images sometimes appear distorted due to the nonspecific sizes of the Bitmaps and the fact they then get stretched to fill the whole box regardless, but the Stretch sizemod is the closest to the kind I need.

None of the other sizemodes suit my needs so I know now I need to create a function to resize the Bitmap and here was the start of my attempt until I realized I was going in completely the wrong direction, the image returned here retains no 'scale'.

    private Bitmap ResizeBitmap(Bitmap img)
    {
        int newWidth = 0;
        int newHeight = 0;
        double imgRatio;

        if (img.Width > img.Height)
        {
            imgRatio = ((double)img.Height / (double)img.Width) * 100;

            newWidth = pictureBox.Width;

            newHeight = (int)(((double)newWidth / 100) * imgRatio);
        }
        else
        {
            imgRatio = ((double)img.Width / (double)img.Height) * 100;

            newHeight = pictureBox.Height;

            newWidth = (int)(((double)newHeight / 100) * imgRatio);
        }

        Bitmap newImg = new Bitmap(newWidth, newHeight);

        using (Graphics g = Graphics.FromImage(newImg))
            g.DrawImage(img, 0, 0, newWidth, newHeight);

        return newImg;
    }

I've been staring at the screen for a while now and the math to do the scaling currently eludes me, I'm hoping someone can point me in the right direction. It's almost 4am so maybe my brain just isn't grasping some simple concepts.

like image 858
Mitch Avatar asked Jan 08 '13 03:01

Mitch


Video Answer


1 Answers

Set the PictureBoxSizeMode to Zoom. This maintains the aspect ratio.

like image 96
Blorgbeard Avatar answered Sep 20 '22 01:09

Blorgbeard