油漆方法闪烁

时间:2013-03-03 13:11:40

标签: c# doublebuffered

考虑以下绘画功能(缩写):

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对象,闪烁会消失。事实上,它没有。起初,我认为绘画方法会花费很长时间,这可能不是(我每次通话测量4-7毫秒)。如果我将cond设置为true,它仍然会闪烁,尽管paint-method几乎没有时间。重要的是paint-method将在面板上绘制,并且我使用计时器大约每50毫秒使面板无效。我怎么能最终消除闪烁?

1 个答案:

答案 0 :(得分:2)

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

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);
    }                                          
  }
}