Friday, November 19, 2010

Flicker Free Animation in C#.NET

For all those guys who are facing the problem of flickering screen while programming a game or while creating an animation, here's the solution...

Basically, your game window flickers because you're trying to repeatedly paint the game directly on the screen. You perform some calculations on the graphics, paint it on the screen,wait for some time(in milliseconds) and then refresh(clean) the screen and repeat this procedure again and again in a loop and flickering becomes inevitable.

But there's a way around this. It's called Double Buffering. Instead of painting on the screen directly you can manipulate the graphics and paint it on an image in memory and all you have to do is paint this image on the screen and you have a neat game.

Here's the code in C#.NET

//graphics object that will manipulate the image in memory
Graphics memgrph;

//the image that is buffered
Bitmap memimg;

memimg = new Bitmap(this.Width, this.Height);

//attaching the graphics object to the buffered image
memgrph = Graphics.FromImage(memimg);


//graphics object that will paint on screen
Graphics screengrph = this.CreateGraphics();
//perform graphics manipulation using memgrph;

//e.g memgrph.DrawRectangle(.....);
//
//

//now draw the image on screen using screengrph
screengrph.DrawImage(memimg,0,0);


2 comments:

  1. in the code "this" refers to the control on which painting is to be done... eg.the Form...

    ReplyDelete