When you draw a custom image, or control, and you would like to resize or move that, you can find,the graphical object is flickering. You can stop this flickering, if you use double buffer technic.
Double buffer works with two layer. The front layer, what you see int he screen, the background layer, is, whar you paint. If the paint method is finish, you just change the background and front layers.
The .NET windows forms control has a built-in double buffering. The Control base class has a SetStyle method. You can set here the double buffer layering.
public partial class DoubleLayerBuffering : UserControl
{
public DoubleLayerBuffering()
{
InitializeComponent();
//Set double buffering in the constructor
SetStyle(ControlStyles.AllPaintingInWmPaint
ControlStyles.OptimizedDoubleBuffer, true);
}
private void DoubleLayerBuffering_Paint(object sender,
PaintEventArgs e)
{
//You can do coustom painting, if use e.Graphics.
//For example:
e.Graphics.DrawRectangle(new SolidBrush(Color.Black),
new Rectangle(10, 10, 20, 20));
}
}
To use double buffering .NET Framework is very simple, and clear, you cant do anything, just set the control style int the constructor.
In .NET Compact Framework you cant find SetStyle method. You must write your own double buffering algorithm. The next example shown, how to do that.
private void Form1_Paint(object sender, PaintEventArgs e)
{
Bitmap doubleBuffer = new Bitmap(Width, Height);
Graphics graphics = Graphics.FromImage(doubleBuffer);
DrawMyCustomControl(graphics);
e.Graphics.DrawImage(doubleBuffer, 0, 0);
}
private void DrawMyCustomControl(Graphics graphics)
{
//You can do coustom painting, if use graphics.
//For example:
graphics.DrawRectangle(new SolidBrush(Color.Black),
new Rectangle(10, 10, 20, 20));
}
The double layer buffeing is not a big magic, but if you use, you get a nicer applications, smooth moveing, and not flickering.
updating:
So, I try to use double layer buffering, and I fing, something is not ok. When my control is refreshing, I find a short white flickering.
If you override OnPaintBackground this flickering is stop.
protected override void OnPaintBackground(PaintEventArgs e)
{
//Do nothing!
}
So, if you want a totaly smooth and flickerless application, first of all override OnPaintBackground, where do nothing. After override OnPaint, and use double layer buffering. On the OnPaint first paint the background, then paint the forground.
updating 2:
I find, my Double layer buffering application tip has a memory leak. After draw backgound layer, you must dispose tihis. The correct solution is:
private void Form1_Paint(object sender, PaintEventArgs e)
{
Bitmap doubleBuffer = new Bitmap(Width, Height);
Graphics graphics = Graphics.FromImage(doubleBuffer);
DrawMyCustomControl(graphics);
e.Graphics.DrawImage(doubleBuffer, 0, 0);
doubleBuffer.Dispose();
graphics.Dispose();
}
Tuesday, 30 June 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment