【问题标题】:Paint method flickering画法闪烁
【发布时间】:2013-03-03 13:11:40
【问题描述】:

考虑以下绘制函数(缩写):

public void paint(object sender, PaintEventArgs e)
{
    base.OnPaint(e);

    Graphics g = e.Graphics;

    BufferedGraphicsContext context = BufferedGraphicsManager.Current;
    BufferedGraphics buffer = context.Allocate(g, e.ClipRectangle);

    buffer.Graphics.Clear(Color.PaleVioletRed);

    // skip drawing if cond is true (condition is not relevant)
    if(!cond)
    {
        try
        {
          // l is some List<p>
          foreach(Point p in l)
          { 
             // ...calculate X and Y... (not relevant)

             buffer.Graphics.FillEllipse(new SolidBrush(Color.Blue), p.X,p.Y, Point.SIZE,Point.SIZE);
           }                                          
         }

         catch {} // some exception handling (not relevant)

         finally{
            buffer.Render(g);
         }
    }                
    buffer.Render(g);
}

请注意,上面的代码或多或少是伪代码。我希望使用 BufferedGraphics 对象,闪烁会消失。事实上,它没有。起初,我认为paint-method 会花费很长时间,但它可能不会(我测量了每次调用 4-7 毫秒)。如果我将cond 设置为true,它仍然会闪烁,尽管paint-method 几乎不需要时间。绘画方法将在面板上绘画并且我使用计时器大约每 50 毫秒使面板无效可能很重要。我怎样才能最终消除闪烁?

【问题讨论】:

  • 终于需要了吗?无论如何,您都在渲染。
  • 谢谢,真的不需要。但是,问题依然存在。
  • 您的代码没有消除闪烁的主要原因,即由 OnPaintBackground() 完成的绘图。支持 Winforms 中对双缓冲的内置支持。检查this answer 以获得双缓冲面板。或者,如果您不需要滚动支持,则只需使用 PictureBox,这是默认打开双缓冲的最基本控件。
  • 感谢您对 PictureBox 的提示!

标签: c# doublebuffered


【解决方案1】:

只需尝试在构造函数中设置属性:

this.DoubleBuffered = true;

那么你不应该需要 BufferedGraphics 的东西:

public void paint(object sender, PaintEventArgs e)
{
  base.OnPaint(e);

  Graphics g = e.Graphics;       
  g.Clear(Color.PaleVioletRed);

  // skip drawing if cond is true (condition is not relevant)
  if(!cond)
  {
    // l is some List<p>
    foreach(Point p in l)
    { 
      // ...calculate X and Y... (not relevant)  
      g.FillEllipse(new SolidBrush(Color.Blue), p.X,p.Y, Point.SIZE,Point.SIZE);
    }                                          
  }
}

【讨论】:

  • 感谢您的回答。不幸的是,面板没有这样的属性。我担心可能会有一点误解:paint 是我的 onPaint 事件监听器,我不是从 Panel 派生的。
  • @MaxBeikirch 尝试从面板派生。或者你可以使用一些反射:How to double buffer .NET controls on a form?
  • 源自面板中的唯一解决方案。我希望我可以避免这种情况,但遗憾的是它不起作用。感谢您的回答!
猜你喜欢
  • 2011-12-02
  • 2012-03-12
  • 2011-03-30
  • 2011-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-04
相关资源
最近更新 更多