Search

Thursday, October 15, 2009

Double Buffering in .NETCF windows Mobile and way to avoid flicker

flickering of UI during painting is One of the common problem windows mobile developer come across though now a days silverlight seems to a good promising alternative for UI design, if you still want to use older methods of coding UI then double buffering is a must for smoother UI and only way to avoid flicker.

unlike desktop environment .netcf is missing inbuilt double buffering support that is The setstyle() in .net, only way to overcome is we have to handle double buffering ourselves, i really curse MS for not porting setstyle() to Compact Framework.

the main reason for flickering is while drawing graphics onto the screen the delay between the calculation time and drawing each data to screen such as Ellipse, Line, Image, Polygon, Rectangle, String etc seems to flicker one way to do is cache it by drawing everything to bitmap and writing it to the screen at one shot see the below example for a brief idea.

Painting without double buffering

protected override void OnPaint(PaintEventArgs e )
{
//Some drawing logic
Graphics gr = e.Graphics;
gr.DrawImage(image, 0, 0);
Graphics gr = e.Graphics;
gr.DrawImage(image, 0, 0);
gr.DrawRectangle(pen, this.ClientRectangle);
}


Painting with double buffering

protected override void OnPaint(PaintEventArgs e )
{
Graphics g; //Offscreen graphics

if (bmpBuff == null) //Bitmap for doublebuffering
{
bmpBuff = new Bitmap(ClientSize.Width, ClientSize.Height);
}

g = Graphics.FromImage(bmpBuff);

g.Clear(this.BackColor);
//Draw some bitmap
g.DrawImage(bmpParent, 0, 0, bmpRect, GraphicsUnit.Pixel);

//Boundary rectangle
Rectangle rc = this.ClientRectangle;
rc.Width--;
rc.Height--;

//Draw boundary
g.DrawRectangle(new Pen(Color.Black), rc);
//Draw from the memory bitmap
e.Graphics.DrawImage(bmpBuff, 0, 0);

base.OnPaint(e);
}

the technic is simple cache/draw everything to bitmap and draw at once on paint method but this comes with the expense of memory so the trade of is very important and is worth for smoother UI and another important thing to remember is never write any logic to calculate in paint method all the basic calculation should be outside the paint method and paint method should just contain simple code to paint the values on to the screen and any more suggestion or trick to avoid flickering is welcome.

2 comments:

Samuel john MVP said...

silverlight is better choice for designing ui and watch out for more improvements in this area

jacklong said...

Is it possible to avoid flickering for standard controls...i.e., I am using label in .net cf which will flicker or display slowly when "\n" is used in text of label..

Post a Comment

Other Interesting Articles



Related Article Widget by Yogith

Search Powered by Google