油漆方法闪烁

本文关键字:闪烁 方法 | 更新日期: 2023-09-27 18:01:51

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

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几乎不需要花费时间,但它仍然闪烁。重要的是,paint-method将在面板上进行绘制,并且我使用计时器大约每50毫秒使面板无效。我怎样才能最终消除闪烁?

油漆方法闪烁

试着在构造函数中设置这个属性:

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