简体   繁体   中英

How to draw on a picturebox and save it in Winforms C#?

I'm making a simple graphic editor in Windows Forms (C#), and I'm using a PictureBox for my canvas. I want to implement the "undo" functionality. I'm drawing using System.Drawing.Graphics . Here is my situation:

  • If I use picturebox.CreateGraphics() , then I will see the drawing, but it won't actually be made on the image (if afterwards I called pictureBox.Image.Save(...) , the saved image would be blank).

  • If I use Graphics.FromImage(picturebox.Image) , then the drawing will be actually made on the image, but I won't see anything.

How can I have both?

And how do I implement the undo functionality after that? I tried using Save() and Restore() on graphics, but it didn't work, maybe I misunderstood what these methods mean.

You should avoid using CreateGraphics since that is a temporary drawing that can get erased by minimizing the form or having another form overlap the graphic area, etc.

To update the PictureBox, just invalidate it after you have an update to the drawing:

pictureBox1.Invalidate();

The Undo-Redo is a different beast. That requires you to keep a list of things to draw and in order to undo something, you remove the item from the list and redraw the whole thing again from the active list.

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