2012-05-23 62 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',而不是一個新的控制。 –