图形保存/恢复状态不起作用

本文关键字:状态 不起作用 恢复 保存 图形 | 更新日期: 2023-09-27 18:18:38

我有一个简单的代码,我不知道如何在pictureBox上加载以前的图形状态,有两个按钮保存(button1)和加载(button2)状态和一个pictureBox。

    public Graphics g;
    public System.Drawing.Drawing2D.GraphicsState aState;
    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        SolidBrush brush = new SolidBrush(Color.Black);
        this.g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        this.g.FillEllipse(brush, e.X, e.Y, 5, 5);
        pictureBox1.Refresh();
    }
    private void Form1_Shown(object sender, EventArgs e)
    {
        this.g = Graphics.FromImage(pictureBox1.Image);
    }
    private void button2_Click(object sender, EventArgs e)
    {
        this.g.Restore(this.aState);
    }
    private void button1_Click(object sender, EventArgs e)
    {
        this.aState = this.g.Save();
    }

图形保存/恢复状态不起作用

我认为您正在尝试存储图像,而不是状态。graphics State仅存储graphics对象中的转换,而不是当前图片,而是平移或SmoothingMode中的更改。

所以我猜你需要像这样存储图片:

Graphics g;
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    SolidBrush brush = new SolidBrush(Color.Black);
    this.g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
    this.g.FillEllipse(brush, e.X, e.Y, 5, 5);
    pictureBox1.Refresh();
}
private void Form1_Shown(object sender, EventArgs e)
{
    this.g = Graphics.FromImage(pictureBox1.Image);
    buffer = new Bitmap(pictureBox1.Image);
    bufferGraphics = Graphics.FromImage(buffer);
}
Image buffer;
Graphics bufferGraphics;
private void button1_Click(object sender, EventArgs e)
{
    bufferGraphics.DrawImage(pictureBox1.Image,0,0);
}
private void button2_Click(object sender, EventArgs e)
{
    this.g.Clear(Color.Transparent);
    this.g.DrawImage(this.buffer, 0, 0);
    pictureBox1.Refresh();
}

看看你的代码,你并没有做什么太疯狂的事情——有没有什么方法可以直接绘制到BackBuffer?通常,当我写这样的东西时,我会在类中创建一个位图,比如_backBuffer。我通过图形所做的所有更改都在这个_backBuffer上,然后我将_backBuffer渲染到PictureBox上。

所以流看起来像…

MouseMove——在_backBuffer上绘制细节;在pictureBox1上调用Invalidate()。pictureBox1有一个自定义的油漆覆盖,将渲染_backBuffer到自己。

在这一点上,您应该基本OK -事情正在绘制。但是,你会想保存它,对吧?

所以你需要再创建一个位图——命名为_savedBitmap。当你点击Button1,你将使用图形。FromImage(我相信)上的_savedBitmap和渲染_backBuffer到它。Button2也会做同样的事情——但是相反——将_savedBitmap渲染到_backBuffer上。

希望有帮助!

编辑:这里有一个链接,解释了一些工作原理:简单的c#游戏,只有本地库