如何使用c#撤消绘制操作

rag*_*ghu 1 .net c#

我在picturebox中加载了一个图像.我通过鼠标点击事件对图像执行绘制操作.当点击鼠标时,它会绘制一个黑色的小矩形区域.现在我想实现撤消操作这个.当我点击一个按钮时,最后的绘画操作应该被撤消.这是我的绘画操作代码..

      private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
    {

            rect.Width = 0;
            rect.Height = 0;
            pictureBox1.Invalidate();


            int radius = 10; //Set the number of pixel you want to use here
            //Calculate the numbers based on radius
            int x0 = Math.Max(e.X - (radius / 2), 0),
                y0 = Math.Max(e.Y - (radius / 2), 0),
                x1 = Math.Min(e.X + (radius / 2), pictureBox1.Width),
                y1 = Math.Min(e.Y + (radius / 2), pictureBox1.Height);
            Bitmap bm = pictureBox1.Image as Bitmap; //Get the bitmap (assuming it is stored that way)
            for (int ix = x0; ix < x1; ix++)
            {
                for (int iy = y0; iy < y1; iy++)
                {
                    bm.SetPixel(ix, iy, Color.Black); //Change the pixel color, maybe should be relative to bitmap
                }
            }
            pictureBox1.Refresh(); //Force refresh
          }
Run Code Online (Sandbox Code Playgroud)

任何人请帮助我如何撤消上次执行的操作.

Den*_*ick 5

因为您在内存中使用光栅图像,所以不能只撤消操作.可以有多种解决方案:

  1. 将原始图像保留在内存中,并为每个操作保留绘图参数:绘制的内容,位置,颜色.当您需要撤消时,您只需要从头到尾重复所有操作(您可能还有一个存储中间图像的控制点)
  2. 在每次操作之后保留图像的快照 - 这将非常耗费内存.在撤消时 - 恢复列表中的上一张图片.
  3. 保持更改的像素 - 在每个操作上分析前一个图像和新图像并保持像素更改.您可以通过复制这些像素来恢复到之前的状态.

  • 谷歌的"C#图像到字节数组","C#存储图像"等.这将为您提供如何使用图像作为字节数组(第2和第3)的一般想法. (2认同)