C#中的WinForms双缓冲? [英] C#, double buffer in WinForms?

查看:160
本文介绍了C#中的WinForms双缓冲?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

        private void button3_Click(object sender, EventArgs e)
    {

        this.DoubleBuffered = true;

            for (int i = 0; i < 350; i++)
            {
                using (Graphics g = this.CreateGraphics() )
                {
                    g.Clear(Color.CadetBlue);
                    g.DrawImage(Properties.Resources._256, 100, 100, i-150, i-150);
                }
            }
    }



然而,以为我有DoubleBuffered设置为true,图像仍然闪烁。任何想法我做错了?
谢谢!

Yet thought I have the DoubleBuffered set to true, the image still flickers. Any ideas what am I doing wrong? Thanks!

推荐答案

随着尼尔指出,你不需要(也不应该)创建一个新的图形对象中的循环的每次迭代。这些都是比较昂贵的资源,不应该创建威利愿意不愿意。

As Neil noted, you don't need to (and shouldn't) create a new Graphics object in each iteration of the loop. These are relatively expensive resources and should not be created willy nilly.

此外,你不应该像画通过调用的createGraphics点击一个按钮处理程序里面。它会导致问题,最主要的是你的图纸是百废待兴的油漆处理程序被调用时(即每窗外是时间收到WM_PAINT消息,并刷新)。你应该通过重写的OnPaint做你的画,简单地调用invalidate(),当你需要更新你的表单。

Also, you shouldn't be painting like that inside of a button Click handler by calling CreateGraphics. It can lead to problems, most notably your drawing being "undone" when the paint handler is invoked (i.e., every time the window is receives a WM_PAINT message and is refreshed). You should do all of your painting by overriding OnPaint and simply call Invalidate() when you need to update your form.

至于闪烁,设置DoubleBuffered为true,通常会照顾它,但滚动您自己的双缓冲实在是微不足道。试一试。也认识到,在这样的一个可能环描绘是不是你想要做什么。如果你想每隔一段时间更新一次使用计时器。您的代码正在快速执行的循环可以执行,这通常不希望。

As for the flickering, setting DoubleBuffered to true will usually take care of it, but rolling your own double buffering is trivial. Give it a try. Also realize that drawing in a loop like that probably isn't what you want to do. Use a timer if you want to update once per some interval. Your code is being executed as fast as the loop can execute, which is not usually desirable.

private void someTimer_Tick( ... )
{
    Invalidate();
}
protected override void OnPaint( PaintEventArgs e )
{
    using( var tempBmp = new Bitmap( ... ) )
    using( var g = Graphics.FromImage( tempBmp ) )
    {
        // draw to tempBmp
        e.Graphics.DrawImage( tempBmp, new Point( 0, 0 ) );
    }
}

这篇关于C#中的WinForms双缓冲?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆