Double buffering with Panel

白昼怎懂夜的黑 提交于 2019-11-27 08:59:31
Hans Passant

Use a PictureBox if you don't need scrolling support, it is double-buffered by default. Getting a double-buffered scrollable panel is easy enough:

using System;
using System.Windows.Forms;

class MyPanel : Panel {
    public MyPanel() {
        this.DoubleBuffered = true;
        this.ResizeRedraw = true;
    }
}

The ResizeRedraw assignment suppresses a painting optimization for container controls. You'll need this if you do any painting in the panel. Without it, the painting smears when you resize the panel.

Double-buffering actually makes painting slower. Which can have an effect on controls that are drawn later. The hole they leave before being filled may be visible for a while, also perceived as flicker. You'll find counter-measures against the effect in this answer.

If acceptable you can stop refreshing the panel while resizing and enable it again after, this way you get rid of the ugly flickering.

I should have posted my solution a long time ago...

Well, here is my solution:

Bitmap buffer = new Bitmap(screenWidth, screenHeight);//set the size of the image
System.Drawing.Graphics gfx = Graphics.FromImage(buffer);//set the graphics to draw on the image
drawStuffWithGraphicsObject(gfx);//draw
pictureBox1.Image = buffer;//set the PictureBox's image to be the buffer

Makes me feel like a complete idiot for finding this solution years after asking this question.

I have tried this with a Panel, but it has proven to be slower when applying the new image. Somewhere I had read, that it is better to use Panel instead of PictureBox. I don't know if I have to add something to the code to speed things up for the Panel, though.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!