图片框位图缩放 [英] Picturebox Bitmap Scaling

查看:27
本文介绍了图片框位图缩放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

当使用 Stretch PictureBoxSizeMode 时,正如您所想象的那样,由于位图的非特定大小以及它们随后被拉伸以填充整个框的事实,图像有时会出现扭曲,但无论如何,但是 Stretch sizemod最接近我需要的那种.

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;
    }

我盯着屏幕已经有一段时间了,目前我无法计算进行缩放的数学运算,我希望有人能指出我正确的方向.现在快凌晨 4 点了,所以也许我的大脑没有掌握一些简单的概念.

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.

推荐答案

将 PictureBoxSizeMode 设置为 缩放.这会保持纵横比.

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

这篇关于图片框位图缩放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆