在我的表单中,我试图使撤消按钮起作用。我使用pictureBox1绘制正方形,使用pictureBox2显示绘制的历史记录。

功能性

在Picturebox mouseup事件中,我将所有绘制的对象添加到列表数组中,因此稍后当我单击“撤消”按钮时,应该可以显示我绘制的矩形的历史记录。因此,如果我在picturebox1上有4个矩形,然后单击“撤消”,picturebox2应该显示3个矩形。如果我再次单击撤消按钮,picturebox2应该显示2个矩形。

问题是当我单击“撤消”按钮时,它没有按我希望的那样工作。它一直在向我显示我绘制的所有矩形,而没有显示绘制对象的历史。

c# - 从数组中检索正确的PictureBox图像-LMLPHP



    Point startArea;   // mouse-down position
    Point currentArea; // current mouse position
    bool drawingBox;     // busy drawing
    List<Rectangle> rectangleList = new List<Rectangle>(); //previous rectangles
    List<Image> ImageCollection = new List<Image>();
    int ImageHistory;

    private void Test_Load(object sender, EventArgs e)
    {
        pictureBox1.Image = Properties.Resources.background;

    }

    private Rectangle getRectangle()
    {
        return new Rectangle(
            Math.Min(startArea.X, currentArea.X),
            Math.Min(startArea.Y, currentArea.Y),
            Math.Abs(startArea.X - currentArea.X),
            Math.Abs(startArea.Y - currentArea.Y));
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        currentArea = startArea = e.Location;
        drawingBox = true;

    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        currentArea = e.Location;
        if (drawingBox)
        {
            pictureBox1.Invalidate();
        }
    }



    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if(drawingBox)
        {
            drawingBox = false;
            var rc = getRectangle();
            if(rc.Width > 0 && rc.Height > 0)
            {
                rectangleList.Add(rc);
                pictureBox1.Invalidate();
            }
        }
        ImageHistory++;
        ImageCollection.Add(pictureBox1.Image);

    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        if (rectangleList.Count > 0)
        {
            using (var g = Graphics.FromImage(pictureBox1.Image))
            {
                g.DrawRectangles(Pens.Black, rectangleList.ToArray());
                pictureBox1.Invalidate();
            }
        }

        if(drawingBox)
        {
            e.Graphics.DrawRectangle(Pens.Red, getRectangle());

            pictureBox1.Invalidate();
        }

    }

    private void button1_Click(object sender, EventArgs e)
    {
        ImageHistory--;
        pictureBox2.Image = ImageCollection[ImageHistory];
    }
}

最佳答案

更改以下行

ImageCollection.Add(pictureBox1.Image);




ImageCollection.Add((Image)pictureBox1.Image.Clone())

关于c# - 从数组中检索正确的PictureBox图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46996017/

10-12 12:41