2013-07-21 29 views
2

我想繪製飛機從左邊到右邊交叉的動畫。winForm invalidate(rectangle)

public partial class Form1 : Form 
{ 
    Bitmap sky, plane, background;   
    int currentX, currentY; 
    Random rndHeight; 
    Rectangle planeRect;  
    Graphics g; 

    public Form1() 
    { 
     InitializeComponent();     
    } 

    private void Form1_Load(object sender, EventArgs e) 
    {    
     try 
     { 
      sky = new Bitmap("sky.jpg"); 
      plane = new Bitmap("plane1.png"); 

      int planeWidth = plane.Width; int planeHeight = plane.Height;     
     } 
     catch (Exception) { MessageBox.Show("No files!"); } 

     this.ClientSize = new System.Drawing.Size(sky.Width, sky.Height);    
     this.FormBorderStyle = FormBorderStyle.FixedSingle;    

     background = new Bitmap(sky); 
     g = Graphics.FromImage(background); 

     rndHeight = new Random(); 
     currentX = -plane.Width; currentY = rndHeight.Next(0, this.Height); 

     this.BackgroundImage = background; 

     timer1.Interval = 1; 
     timer1.Enabled = true; 
     timer1.Start();    
    } 

    protected override void OnPaint(PaintEventArgs e) 
    {    
     e.Graphics.DrawImage(sky, 0, 0); 
     e.Graphics.DrawImage(plane, planeRect);    
    } 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     g.DrawImage(sky, 0, 0); 
     planeRect.X = currentX; planeRect.Y = currentY; planeRect.Width = plane.Width; planeRect.Height = plane.Height; 
     g.DrawImage(plane, planeRect); 
     Rectangle myNewPlane = new Rectangle(planeRect.X - 10, planeRect.Y - 10, planeRect.Width + 20, planeRect.Height + 20); 
     this.Invalidate(myNewPlane); 
     if (currentX >= this.Width) currentX = -plane.Width; else currentX += 2; 
     currentY += rndHeight.Next(-2, 2);       
    } 
} 

此代碼的工作,但平面的矩形與timer1.Interval的頻率閃爍。我的問題是:我怎樣才能避免這些閃爍?

p.s .:背景圖像分辨率1024x768;飛機 - 160x87。飛機是透明的

+1

您是否嘗試過'this.DoubleBuffered = true;' –

+0

期待每秒* 1000 *幀是非常不現實的。如果你想要高動畫速度,使用DoubleBuffered屬性實際上是錯誤的,它不是免費的。使用一個切合實際的計時器間隔,這樣您至少可以在每臺機器上獲得一致的速率。 31毫秒是一個很好的價值。而是重寫OnPaintBackground,所以你不需要雙緩衝。使用PixelFormat.Format32bppArgb進行快速渲染,速度比所有其他渲染快十倍。 –

回答

2

您可以通過爲您的窗體設置DoubleBuffering樣式來消除閃爍來解決此問題。

DoubleBuffered = true; 

你可能要設置一些更多的控制樣式,以及自動雙緩衝(InitializeComponents後)約自動和手動雙緩衝

this.SetStyle(
    ControlStyles.AllPaintingInWmPaint | 
    ControlStyles.UserPaint | 
    ControlStyles.DoubleBuffer,true); 

更多信息,MSDN上here