如何拉伸位图以填充PictureBox [英] How to stretch a Bitmap to fill a PictureBox

查看:159
本文介绍了如何拉伸位图以填充PictureBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要拉伸各种尺寸的位图以填充PictureBox. PictureBoxSizeMode.StretchImage可以满足我的需要,但无法想到使用此方法向图像中正确添加文本或行的方法.下图是一个5x5像素的位图,并拉伸到了380x150 PictureBox.

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

我尝试适应此示例此示例这种方式

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

但是得到这个

我想念什么?

解决方案

看来您正在抛弃想要在图片框中看到的位图(bmp2)!来自using块之所以使用您发布的示例,是因为代码返回后,该代码不再需要Bitmap对象.在您的示例中,您需要使用位图,因此bmp2变量上没有using -block.

以下应能工作:

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

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?

解决方案

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

这篇关于如何拉伸位图以填充PictureBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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