【问题标题】:Save Panel to Bitmap c# Winforms将面板保存到位图 c# Winforms
【发布时间】:2023-03-30 20:41:01
【问题描述】:

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

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

这里是一些sn-ps的代码:

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

Graphics GD_LD;

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

GD_LD = Graphics.FromHwnd(panelDrawLD.Handle);

然后我有用于Panel的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);

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

我看到了一些关于这个主题的帖子,但我无法适应我的情况。

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

【问题讨论】:

标签: c# winforms graphics panel gdi+


【解决方案1】:

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

此外,如果您创建 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));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多