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.
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.
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
}