【发布时间】:2021-01-11 21:57:29
【问题描述】:
我在 C# Winforms 面板中绘制图像:
private void DrawPanel_Paint(object sender, PaintEventArgs e)
{
DrawOnPanel(e.Graphics);
}
调用的方法从我的资源 (myImage) 中获取现有图像,将其提供给另一个方法,该方法调整图像大小并返回调整大小的图像以便绘制。
public static void DrawOnPanel(Graphics g)
{
var _resizedImage = ResizeImage(Resources.myImage);
g.DrawImage(_resizedImage, destX, destY);
// ... several other images resized & manipulated then drawn
}
调整图片大小的功能是:
public Bitmap ResizeImage(Bitmap image)
{
int scale = 3;
var destImage= new Bitmap(image.Width * scale, image.Height * scale);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(destImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighSpeed;
graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
graphics.SmoothingMode = SmoothingMode.HighSpeed;
graphics.PixelOffsetMode = PixelOffsetMode.None;
using var wrapMode = new ImageAttributes();
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
return destImage;
}
程序在其循环中不断调用 DrawPanel.Invalidate()。
每次调用 DrawPanel.Invalidate() 时,我都会检测到内存泄漏。在 GC 处理它之前,内存消耗正在稳步上升。虽然这不是一个破坏游戏的问题,但我仍然想知道我应该在哪里以及如何在上面的代码中处理我的对象。
我尝试在上述DrawOnPanel 方法中使用using var _resizedImage = ResizeImage(Resources.myImage);,但程序返回错误System.ArgumentException: 'Parameter is not valid.'。如果我删除 using 则没有错误。
【问题讨论】:
-
请发布有意义的代码。此外,您不需要任何这些:将资源图像分配给字段对象或集合,然后使用图形对象绘制调整大小的图像。它有一个超载。表单关闭时处理图像。 -- 请记住,资源是一个工厂(如果它来自
Properties.Resources),它会在您每次请求时创建一个新图像对象。 -
but the program returns an error here the second time I invalidate the screen.twitter.com/marcgravell/status/1330430245384679424?s=20 -
我们需要查看
destImage的声明位置。请分享minimal reproducible example。 -
(对上面的代码做了一些更正,destImage在ResizeImage方法的开头声明。)问题出在DrawOnPanel方法中的using语句。当我运行程序时,它返回一个参数无效错误。我知道代码可以优化,但我想知道我应该在哪里处理对象 _resizedImage?
标签: c# winforms object bitmap dispose