Mathew O'Dwyer Mathew O'Dwyer - 13 days ago 7
C# Question

How does this code work? (GDI, C#) [SOLVED]

I was just wondering if anyone could shed some light onto this for me. I've been coding c# for years but never even touched anything in the System.Drawing namespace except for the bitmap class and I've been following some tutorials and came up with some code that works. I'm developing a 2D Game Engine and the code below is for the graphics engine, which uses GDI. However, I just don't understand how this code is even working. Here it is:

private Graphics frontBuffer;
private Graphics backBuffer;
private Bitmap backBufferBitmap;

public void Initialize()
{
backBufferBitmap = new Bitmap(game.Form.Width, game.Form.Height);
frontBuffer = game.Form.CreateGraphics();
backBuffer = Graphics.FromImage(backBufferBitmap);
}

public void Update()
{
try
{
frontBuffer.DrawImageUnscaled(backBufferBitmap,0,0);
backBuffer.Clear(Color.Black);
}
catch(Exception e)
{
throw e;
}
}


So, the main part that's confusing to me is this;

How is the back buffer bitmap getting updated? and why is the back buffer being cleared and not the front buffer?

Also, the initialize method is called once and the update method is called once per frame in a while loop.

Answer

After you initialize the backBuffer graphics objects from the bitmap, every time you say, for example backBuffer.DrawLine(...) GDI+ will do the pixel manipulations directly on this Bitmap. They are linked in a way. Think of backBufferBitmap as the canvas, and of backBuffer as the brush.

The frontBuffer is initialized from the form instead. So the form is it's canvas and whatever you do with frontBuffer is drawn to the form - in this case here it draws the backBufferBitmap.

It's basically a double-buffering scheme, that has a lot of advantages over directly drawing your lines and circles to the form, e.g. less flickering. Whenever you draw something to a form, remember that it is removed very often (e.g. when you move the form outside of the screen area). You would need to refresh it using the form's Paint event.

After Update() is called, you would need to redraw your scene to backBuffer, before you call Update again, because the bitmap is blacked out by your Clear() after it is drawn to the screen.