如何拉伸位图以填充图片框
我需要拉伸各种大小的位图来填充图片框。 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;
}
但得到这个
我缺少什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看来您正在丢弃您希望在图片框中看到的位图 (
bmp2
)!来自 使用您发布的示例是因为代码返回后不再需要Bitmap
对象。在您的示例中,您需要位图来保留,因此bmp2
变量上没有using
块。以下应该有效:
It appears you're throwing away the bitmap (
bmp2
) you'd like to see in your picture box! Theusing
block from the example you posted is used because the code no longer needs theBitmap
object after the code returns. In your example you need the Bitmap to hang around, hence nousing
-block on thebmp2
variable.The following should work:
当您在绘制方法中出现异常时,会出现白色背景上的红色 X。
您的错误是您试图将已处理的位图指定为图片框的图像源。使用“using”关键字将处理您在图片框中使用的位图!
因此,我知道,您的异常将是 ObjectDisposeException :)
您应该创建一次位图并保留它,直到不再需要为止。
如果您需要这样做以释放资源,此功能将允许您替换旧位图并处理前一个位图。
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.
This function will allow you to replace the old bitmap disposing the previous one, if you need to do that to release resources.