简体   繁体   English

Picturebox位图缩放

[英]Picturebox Bitmap Scaling

I have a Picturebox and a ton of Bitmaps that can be displayed in it. 我有一个PictureboxPicturebox可以在其中显示的Bitmaps 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. 当您使用Stretch PictureBoxSizeMode ,由于Bitmaps的非特定大小,图像有时会显得扭曲,然后它们会被拉伸以填充整个框,但是Stretch sizemod最接近我需要的类型。

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'. 没有其他尺寸模式适合我的需要所以我现在知道我需要创建一个函数来调整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;
    }

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. 现在差不多凌晨4点,所以也许我的大脑并没有抓住一些简单的概念。

Set the PictureBoxSizeMode to Zoom . 将PictureBoxSizeMode设置为Zoom This maintains the aspect ratio. 这保持了纵横比。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM