如何在图片框上绘图并将其保存在Winforms C#中?

时间:2023-01-30 20:53:29

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:

我正在Windows Forms(C#)中创建一个简单的图形编辑器,我正在使用PictureBox作为我的画布。我想实现“撤消”功能。我正在使用System.Drawing.Graphics绘图。这是我的情况:

  • 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).

    如果我使用picturebox.CreateGraphics(),那么我将看到绘图,但它实际上不会在图像上进行(如果之后我调用了pictureBox.Image.Save(...),保存的图像将为空白) 。

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

    如果我使用Graphics.FromImage(picturebox.Image),那么绘图将实际在图像上进行,但我什么都看不到。

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.

那之后如何实现撤消功能呢?我尝试在图形上使用Save()和Restore(),但它不起作用,也许我误解了这些方法的含义。

1 个解决方案

#1


3  

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.

您应该避免使用CreateGraphics,因为这是一个临时绘图,可以通过最小化窗体或使另一个窗体重叠图形区域等来删除。

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

要更新PictureBox,只需在更新绘图后使其无效:

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.

Undo-Redo是一个不同的野兽。这需要您保留要绘制的内容列表,并且为了撤消某些内容,您从列表中删除该项目并从活动列表中重新绘制整个内容。

#1


3  

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.

您应该避免使用CreateGraphics,因为这是一个临时绘图,可以通过最小化窗体或使另一个窗体重叠图形区域等来删除。

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

要更新PictureBox,只需在更新绘图后使其无效:

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.

Undo-Redo是一个不同的野兽。这需要您保留要绘制的内容列表,并且为了撤消某些内容,您从列表中删除该项目并从活动列表中重新绘制整个内容。