Picturebox位图缩放

Mit*_*tch 5 c# winforms

我有Picturebox一吨的Bitmaps可显示在其中.与其他位置相比,位图的相对大小对用户来说很重要.他们需要能够看到一个图像比另一个图像更小或更大.位图也必须完全适合图片框,并且无法调整图片框的大小.

当简单地在巨大的图片框中显示未缩放的位图时,位图的相对大小很容易看到,但是当试图将它们放在一个小盒子中并且必须缩小它们时我的问题就开始了.

PictureBoxSizeMode你想象使用Stretch时,由于Bitmaps的非特定大小,它们有时会显得扭曲,然后它们会被拉伸以填充整个盒子,但是Stretch sizemod最接近我需要的那种.

没有其他尺寸模式适合我的需要所以我现在知道我需要创建一个函数来调整Bitmap的大小,这是我尝试的开始,直到我意识到我的方向完全错误,这里返回的图像没有保留".

    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;
    }
Run Code Online (Sandbox Code Playgroud)

我一直盯着屏幕看了一会儿,目前我不知道做缩放的数学,我希望有人可以指出我正确的方向.现在差不多凌晨4点,所以也许我的大脑并没有抓住一些简单的概念.

Blo*_*ard 10

将PictureBoxSizeMode设置为Zoom.这保持了纵横比.