2012-05-23 35 views
2

我试图做双缓冲来摆脱闪烁,但重绘图像闪烁。我需要在一个新的位置在酒吧中用周期性重新绘制图像,它适用于我。但是,当重绘非常明显的闪烁。请帮助。如何为面板制作双缓冲?

namespace CockroachRunning 
{ 
    public partial class Form1 : Form 
    { 
     Random R = new Random(); 
     Semaphore s1 = new Semaphore(2, 4); 
     Bitmap cockroachBmp = new Bitmap(Properties.Resources.cockroach, new Size(55, 50)); 
     List<Point> cockroaches = new List<Point>(); 
     public Form1() 
     { 
      InitializeComponent(); 
      this.DoubleBuffered = true; 
      cockroaches.Add(new Point(18,13)); 
      Thread t1 = new Thread(Up); 
      t1.Start(); 
     } 
     public void Up() 
     { 
      while (true) 
      { 
       s1.WaitOne(); 
       int distance = R.Next(1, 6); 
       for (int i = 0; i < distance; i++) 
       { 
        if (cockroaches[0].Y - 1 > -1) 
        { 
         cockroaches[0] = new Point(cockroaches[0].X, cockroaches[0].Y - 1); 
         panel1.Invalidate();       
        } 
       } 
       s1.Release(); 
       Thread.Sleep(100); 
      } 
     } 
     private void panel1_Paint(object sender, PaintEventArgs e) 
     { 
      Image i = new Bitmap(panel1.ClientRectangle.Width, panel1.ClientRectangle.Height); 
      Graphics g = Graphics.FromImage(i); 
      Graphics displayGraphics = e.Graphics; 
      g.DrawImage(cockroachBmp, cockroaches[0]); 
      displayGraphics.DrawImage(i, panel1.ClientRectangle); 
     } 
    } 
} 

回答

3

为了摆脱闪烁的,我用下面的设置来配置控制的行为:

base.DoubleBuffered = true; 

SetStyle(ControlStyles.AllPaintingInWmPaint, true); 
SetStyle(ControlStyles.ResizeRedraw, true); 
SetStyle(ControlStyles.UserPaint, true); 
SetStyle(ControlStyles.OptimizedDoubleBuffer, true); 
UpdateStyles(); 

我在Control派生类的构造函数中调用此。我不确定这是否也适用于表单,但我会想象它的确如此。

然后在void OnPaintBackground(PaintEventArgs e)(删除客户区)和void OnPaint(PaintEventArgs e)(实际图)中完成绘图。

+1

您提供创建自己的控件继承面板并向设计师添加样式? 像这样: 类MyPanel:面板 { 公共MyPanel(){ // 风格 }} – Creative

+0

@Creative刚刚尝试将代码添加到你的'Form',而不是一个新的控制。 –