【问题标题】:Saving Graphics to Bitmap outside of paint?在绘画之外将图形保存到位图?
【发布时间】:2010-11-29 23:42:36
【问题描述】:

尝试将 C# Winforms 图形对象保存到位图,但我在 Paint 事件之外使用此代码收到 ArgumentException:

public Bitmap Bitmap
{
   get
   {
       return new Bitmap(100, 100, this.Graphics);
   }
}

this.Graphics 只是在 Paint 事件处理程序中设置的地方,我猜该对象在事件之外变得无效,这很烦人,因为我想避免在其中放置代码来保存图像。谁能指出我正确的方向?

编辑: 我将不得不重新考虑我的绘画代码,因为我需要能够将控件“绘制”到位图中。

【问题讨论】:

  • 您能发布完整的错误消息吗?直到:你试过 UserControl.CreateGraphics() 吗?
  • System.ArgumentException:参数无效。在 System.Drawing.Bitmap..ctor(Int32 width, Int32 height, Graphics g) at FlowSharp.FlowChartControl.get_Bitmap() 在 C:\Users\Dan\Documents\My Dropbox\Programming\FlowSharp\FlowChartControl.cs:line 35在 C:\Users\Dan\Documents\My Dropbox\Programming\FlowSharp\FlowSharpForm.cs:line 441 中的 FlowSharp.fFlowSharp.bMPToolStripMenuItem_Click(Object sender, EventArgs e)

标签: c# graphics


【解决方案1】:

是的,这将在 Graphics 对象被释放后进行轰炸。几乎没有理由使用这个构造函数,它只设置位图分辨率。如果这对你来说真的很重要,那么直接使用 Bitmap.SetResolution() 方法。

【讨论】:

    【解决方案2】:

    如果你真的想使用图形可以使用this.CreateGraphics

    public Bitmap Bitmap
    {
        get
        {
            using (var graphics = this.CreateGraphics())
            {
                return new Bitmap(100, 100, graphics);
            }
        }
    }
    

    但是

    return new Bitmap(100, 100);
    

    可能就足够了。

    编辑:
    如果您想修改位图,您可以从该位图创建一个图形对象:

    Bitmap bitmap = new Bitmap(100, 100);
    using (var graphics = Graphics.FromImage(bitmap))
    {
        // modify bitmap
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-09
      • 2018-11-04
      • 1970-01-01
      • 2013-04-02
      • 1970-01-01
      相关资源
      最近更新 更多