简体   繁体   中英

How can I save my drawings(such as rectangle, circle) from panel into image?

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM