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

时间:2014-08-19 17:45:30

标签: c# graphics gdi+ draw picturebox

我有一个简单的代码,我无法弄清楚如何在pictureBox上加载以前的Graphics状态,有两个按钮可以保存(button1)和load(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();
    }

2 个答案:

答案 0 :(得分:2)

看着你的代码,你没有做任何太疯狂的事情 - 无论如何你可以只画一个BackBuffer?通常,当我写这样的东西时,我会创建一个类中的Bitmap,比如_backBuffer。我通过Graphics进行的所有更改都是ON _backBuffer - 然后我将_backBuffer渲染到PictureBox上。

所以流程看起来像......

MouseMove - 在_backBuffer上绘制细节;在pictureBox1上调用Invalidate()。 pictureBox1有一个自定义绘制覆盖,它将_backBuffer渲染到自身。

此时,你应该大部分都没事 - 事情正在酝酿之中。但是,你会想保存它,是吗?

所以你需要再创建一个Bitmap - 称之为_savedBitmap。当你单击Button1时,你将在_savedBitmap上使用Graphics.FromImage(我相信)并渲染_backBuffer。 Button2也会这样做 - 但反之 - 将_savedBitmap渲染到_backBuffer上。

希望有所帮助!

编辑:这是一个链接,解释了一些如何工作: Simple Game in C# with only native libraries

答案 1 :(得分:1)

我认为你试图存储图像,而不是状态。图形状态仅存储transforms in the Graphics object,而不是当前图片,而是存储平滑模式中的平移或更改。

所以我的猜测是你需要存储这样的图片:

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();
}