将面板保存到位图 c# Winforms

Save Panel to Bitmap c# Winforms

我有一个图形对象和一个面板。 Graphics 对象使用 Panel 中的 Handler 实例化。然后,Panel 使用 Paint 操作进行更新。在 Paint 动作中,Graphics 对象用于绘画。有时在代码中我使用 Invalidate() 来更新面板。

我想将Graphics对象的内容或Panel的内容保存到一个文件中。每当我尝试这样做时,都会创建图像文件,但它是空白的。

以下是一些代码片段:

我将 Graphics 对象初始化为 class 变量:

Graphics GD_LD;

然后在构造函数中,我使用以下内容使用面板处理程序实例化对象:

GD_LD = Graphics.FromHwnd(panelDrawLD.Handle);

然后我有在面板的 Paint 动作上使用的绘图函数,我使用 Graphics 对象来制作所有绘图:

private void panelDrawLD_Paint(object sender, PaintEventArgs e)
{
    ..... some code ....
    //Code example
    GD_LD.FillPolygon(blackBrush, getPoints(min, sizeGP, scaleX, scaleY));
    GD_LD.FillPolygon(blackBrush, getPoints(max, sizeGP, scaleX, scaleY));
    ..... some code ....
}

以上方法可以很好地在面板中绘制并始终与绘图保持一致。

问题出在尝试将面板保存到图像文件时:

Bitmap I_LD = new Bitmap(panelDrawLD.Size.Width, panelDrawLD.Size.Height);
panelDrawLD.DrawToBitmap(I_LD, new Rectangle(0,0, panelDrawLD.Size.Width, panelDrawLD.Size.Height));
I_LD.Save(tempPath + "I_LD.bmp",ImageFormat.Bmp);

图像文件已创建但没有内容。只是空白。

我看到了一些关于这个主题的帖子,但我无法根据自己的情况进行调整。

我做错了什么?有什么可能的解决方案?

您真正应该做的是将您的 Paint 事件重构为一个子例程,该子例程将 Graphics 对象作为名为 target 的参数。根据 target 完成所有绘图。然后你可以调用它并从 panelDrawLD_Paint 传递 e.Graphics,然后使用你用 Graphics.FromImage(I_LD).

创建的 Graphics 从你的其他函数调用它

此外,如果您创建 Graphics(或任何其他 GDI 对象),您 必须 销毁它,否则会发生内存泄漏。

像这样:

private void panelDrawLD_Paint(object sender, PaintEventArgs e)
{
    //e.Graphics does NOT need to be disposed of because *we* did not create it, it was passed to us by the control its self.
    DrawStuff(e.Graphics);
}

private void Save()
{
    // I_LD, and g are both GDI objects that *we* created in code, and must be disposed of.  The "using" block will automatically call .Dispose() on the object when it goes out of scope.
    using (Bitmap I_LD = new Bitmap(panelDrawLD.Size.Width, panelDrawLD.Size.Height))
    {
        using (Graphics g = Graphics.FromImage(I_LD))
        {
            DrawStuff(g);
        }
        I_LD.Save(tempPath + "I_LD.bmp", ImageFormat.Bmp); 
    }   
}


private void DrawStuff(Graphics target)
{
    //Code example
    target.FillPolygon(blackBrush, getPoints(min, sizeGP, scaleX, scaleY));
    target.FillPolygon(blackBrush, getPoints(max, sizeGP, scaleX, scaleY));
}