我正尝试使用撤销功能将命令模式调整为简单的绘图应用程序。我一直坚持使用OnPaint
撤销操作事件。这是代码:命令模式和OnPaint事件问题
[解决]在后
interface ICommand {
void Execute();
void UnExecute();
}
class DrawLineCommand : ICommand {
private SimpleImage simpleImage;
private Image prevImage;
public DrawLineCommand(SimpleImage simpleImage) {
this.simpleImage = simpleImage;
this.prevImage = simpleImage.Image;
}
public void Execute() {
simpleImage.DrawLine();
}
public void UnExecute() {
simpleImage.Image = prevImage;
}
}
class CommandManager {
private Stack undoStack = new Stack();
public void ExecuteCommand(ICommand command) {
command.Execute();
undoStack.Push(command);
}
public void UnExecuteCommand() {
if (undoStack.Count > 0) {
ICommand command = (ICommand)undoStack.Pop();
command.UnExecute();
}
}
}
class SimpleImage {
private Point startPoint;
private Point endPoint;
private PictureBox pictureBox;
public SimpleImage(PictureBox pictureBox) {
this.pictureBox = pictureBox;
pictureBox.Paint += new PaintEventHandler(pictureBox_Paint);
}
void pictureBox_Paint(object sender, PaintEventArgs e) {
// this code shows the line during drawing
// this code is under "if operation == drawLine" block
Graphics graphics = e.Graphics;
graphics.DrawLine(Pens.Red, startPoint, endPoint);
// how can i refresh picturebox after undo operation?
// "if operation == undo" then ??
}
public void DrawLine() {
// this code actually saves finally drawn line
Image img = Image;
Graphics graphics = Graphics.FromImage(img);
graphics.DrawLine(Pens.Red, startPoint, endPoint);
Image = img;
}
public void Invalidate() {
pictureBox.Invalidate();
}
public Image Image {
get { return pictureBox.Image; }
set { pictureBox.Image = value; }
}
public Point StartPoint {
get { return startPoint; }
set { startPoint = value; }
}
public Point EndPoint {
get { return endPoint; }
set { endPoint = value; }
}
}
public partial class FormMain : Form {
private PictureBox pictureBox;
private SimpleImage simpleImage;
private CommandManager commandManager;
public FormMain() {
InitializeComponent();
simpleImage = new SimpleImage(this.pictureBox);
commandManager = new CommandManager();
}
void pictureBox_MouseDown(object sender, MouseEventArgs e) {
if (e.Button != MouseButtons.Left)
return;
simpleImage.StartPoint = e.Location;
}
void pictureBox_MouseMove(object sender, MouseEventArgs e) {
if (e.Button != MouseButtons.Left)
return;
simpleImage.EndPoint = e.Location;
simpleImage.Invalidate();
}
void pictureBox_MouseUp(object sender, MouseEventArgs e) {
simpleImage.Invalidate();
commandManager.ExecuteCommand(new DrawLineCommand(simpleImage));
}
}
的端部细节它实际上绘制一条线,则执行命令,并将它推入堆栈。我无法实现UNDO的工作。我的意思是。逐步调试我看到对象从堆栈中弹出,然后OnPaint
执行。但实际上没有显示“以前的”图像。
我已经阅读了很多网站,并且还从一个codeproject网站的/文章中示例了应用程序。它提供了与TextBox
和粗体/斜体操作相同的方法。它像地狱一样工作。唯一的区别是这种残忍的OnPaint
方法..
在此先感谢您的任何建议!
[编辑]在匆忙我忘记了分配一个引用类型到另一种未复制它(创建独立对象),改变此:
this.prevImage = simpleImage.Image;
在几个地方解决了这个问题。现在一切正常..
如果您在得到答案之前解决了问题,您通常会将解决方案发布为您自己问题的答案。然后人们可以对它投票等 – 2011-06-14 17:48:09
哦..这是有道理的;)谢谢你的提示。 – qlf00n 2011-06-14 18:08:50