Saving Graphics to Bitmap outside of paint?

筅森魡賤 提交于 2020-01-17 01:21:13

问题


Trying to save a C# Winforms Graphics Object to a bitmap, yet I am getting an ArgumentException with this code outside of the Paint event:

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

Where this.Graphics is just set in the Paint event handler, I'm guessing the object becomes invalid outside of the event, which is annoying as I'd like to avoid having to put code in there for saving the images. Can anyone point me in the right direction?

Edit: I will have to re-factor my painting code, as I need to be able to 'draw' the control into a bitmap.


回答1:


Yes, this will bomb after the Graphics object is disposed. There is little reason to use this constructor, it only sets the bitmap resolution. If that's actually important to you then just use the Bitmap.SetResolution() method directly.




回答2:


If you really want to use the graphics you can use this.CreateGraphics.

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

but

return new Bitmap(100, 100);

would probably be sufficient.

Edit:
If you want to modify a bitmap you create a graphics object from that bitmap:

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


来源:https://stackoverflow.com/questions/4305168/saving-graphics-to-bitmap-outside-of-paint

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!