Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stretch a Bitmap to fill a PictureBox

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.

using pictureBox.SizeMode = PictureBoxSizeMode.StretchImage

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

using g.DrawImage(bmp, new Rectangle(Point.Empty, bmp2.Size))

What am I missing?

like image 736
jacknad Avatar asked Sep 02 '25 14:09

jacknad


1 Answers

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;
    }
}
like image 78
user7116 Avatar answered Sep 05 '25 03:09

user7116