如何拉伸位图以填充PictureBox [英] How to stretch a Bitmap to fill a 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屋!