How to stretch a Bitmap to fill a PictureBox

守給你的承諾、 提交于 2019-12-10 22:09:15

问题


I need to stretch various sized bitmaps to fill a PictureBox. PictureBoxSizeMode.StretchImage sort of does what I need but can't think of a way to properly add text or lines to the image using this method. The image below is a 5x5 pixel Bitmap stretched to a 380x150 PictureBox.

pictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox.Image = bmp;

I tried adapting this example and this example this way

using (var bmp2 = new Bitmap(pictureBox.Width, pictureBox.Height))
using (var g = Graphics.FromImage(bmp2))
{
    g.InterpolationMode = InterpolationMode.NearestNeighbor;
    g.DrawImage(bmp, new Rectangle(Point.Empty, bmp2.Size));
    pictureBox.Image = bmp2;
}

but get this

What am I missing?


回答1:


It appears you're throwing away the bitmap (bmp2) you'd like to see in your picture box! The using block from the example you posted is used because the code no longer needs the Bitmap object after the code returns. In your example you need the Bitmap to hang around, hence no using-block on the bmp2 variable.

The following should work:

using (bmp)
{
    var bmp2 = new Bitmap(pictureBox.Width, pictureBox.Height);
    using (var g = Graphics.FromImage(bmp2))
    {
        g.InterpolationMode = InterpolationMode.NearestNeighbor;
        g.DrawImage(bmp, new Rectangle(Point.Empty, bmp2.Size));
        pictureBox.Image = bmp2;
    }
}



回答2:


The red X on white background happens when you have an exception in a paint method.

Your error is that you are trying to assign a disposed bitmap as the image source of your picturebox. The use of "using" keyword will dispose the bitmap you are using in the picturebox!

So your exception, i know, will be ObjectDisposedException :)

You should create the bitmap once and keep it until it is not needed anymore.

void ReplaceResizedPictureBoxImage(Bitmap bmp)
{
    var oldBitmap = pictureBox.Image;

    var bmp2 = new Bitmap(pictureBox.Width, pictureBox.Height);
    using (var g = Graphics.FromImage(bmp2))
    {
        g.InterpolationMode = InterpolationMode.NearestNeighbor;
        g.DrawImage(bmp, new Rectangle(Point.Empty, bmp2.Size));
        pictureBox.Image = bmp2;
    }

    if (oldBitmap != null)
        oldBitmap.Dispose();
}

This function will allow you to replace the old bitmap disposing the previous one, if you need to do that to release resources.



来源:https://stackoverflow.com/questions/7920058/how-to-stretch-a-bitmap-to-fill-a-picturebox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!