问题描述
我正在Windows窗体(C#)中创建一个简单的图形编辑器,并且我在画布上使用了 PictureBox
.我想实现撤消"功能.我正在使用 System.Drawing.Graphics
进行绘制.这是我的情况:
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:
-
如果我使用
picturebox.CreateGraphics()
,那么我将看到绘图,但实际上不会在图像上绘制(如果此后我称为pictureBox.Image.Save(...)
,保存的图像将为空白).
If I use
picturebox.CreateGraphics()
, then I will see the drawing, but it won't actually be made on the image (if afterwards I calledpictureBox.Image.Save(...)
, the saved image would be blank).
如果我使用 Graphics.FromImage(picturebox.Image)
,则实际上将在图像上绘制图形,但是我什么也看不到.
If I use Graphics.FromImage(picturebox.Image)
, then the drawing will be actually made on the image, but I won't see anything.
我怎么都可以呢?
在那之后如何实现撤消功能?我尝试在图形上使用 Save()
和 Restore()
,但是它没有用,也许我误解了这些方法的含义.
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.
推荐答案
您应该避免使用CreateGraphics,因为这是一个临时图形,可以通过最小化表单或使其他表单与图形区域重叠等方式将其擦除.
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.
要更新PictureBox,只需在更新图形后将其无效:
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.
这篇关于如何在图片框上绘制并将其保存在Winforms C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!