Reputation: 21
How can I save my drawings(such as rectangle,circle) from panel into image?
I have tried this code but I don't know why it only gives me white image always:
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.DefaultExt = "bmp";
saveFileDialog.Filter = "Bitmap files|*.bmp";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
int width = panel1.Width;
int height = panel1.Height;
Bitmap bitMap = new Bitmap(panel1.Width, panel1.Height);
panel1.DrawToBitmap(bitMap, new Rectangle(0, 0, panel1.Width, panel1.Height));
bitMap.Save(saveFileDialog.FileName);
}
Upvotes: 0
Views: 469
Reputation: 81610
Do not use CreateGraphics for drawing your graphic, since that is only a temporary drawing (it will get erased by other windows or if you minimize the the form, etc).
Use the panel's paint event to do your drawing:
panel1.Paint += panel1_Paint;
void panel1_Paint(object sender, PaintEventArgs e) {
// draw stuff with e.Graphics
}
call the panel's Invalidate method to make the paint method get called again.
Upvotes: 1