2014-02-15 59 views
2

我有一個程序,可以隨意移動圖片框中的gif,但是當函數被調用時,gif會凍結。但是,當我使用keyDown函數移動框來移動圖片框時,它仍然是動畫的。如何在移動時保持動畫效果?如何在不暫停的情況下移動動畫GIF?

這是我用它來移動一個隨機距離,凍結GIF。

void Form1_KeyDown(object sender, KeyEventArgs e) 
{   
    if (e.KeyCode == Keys.A) 
    { 
     eventDuration = randomizer.Next(30, 70); 
     while (eventDuration != 0) 
     { 
      MoveLeft(); 
      eventDuration = eventDuration - 1; 
      Thread.Sleep(15); 
     } 
    } 
} 

private void MoveLeft() 
{ 
    _y = picPicture.Location.Y; 
    _x = picPicture.Location.X; 
    picPicture.Location = new System.Drawing.Point(_x - 1, _y); 
} 

然而,如果利用這一點,它平滑地移動而不凍結GIF,甚至當我按住A鍵。因爲它需要不斷的用戶輸入我不能使用這種方法,而首先是自主的方向它移動

void Form1_KeyDown(object sender, KeyEventArgs e) 
{   
    if (e.KeyCode == Keys.A) 
    { 
     MoveLeft(); 
    } 
} 

private void MoveLeft() 
{ 
    _y = picPicture.Location.Y; 
    _x = picPicture.Location.X; 
    picPicture.Location = new System.Drawing.Point(_x - 1, _y); 
} 

我如何才能將我的圖片框隨機距離無需暫停GIF?

回答

4

如果您使用Thread.Sleep,您的應用程序不處理任何窗口事件,包括重繪。正確的方法是使用Timer class。當按下A鍵時,應在其Tick事件中啓用計時器並移動控件。

或者,您可以撥打Application.DoEvents methodThread.Sleep,但這是一種不好的做法。

0

要在移動時爲GIF製作動畫,您可以在KeyDown()方法上啓動計時器,並在每個Tick處調用MoveLeft()方法。當您想停止動畫時,只需按另一個鍵即可停止定時器。通過這種方式,您可以在移動過程中以及靜止時獲得動畫。

private Timer _timer = new Timer(); 

_timer.Interval = 10; // miliseconds 

void Form1_KeyDown(object sender, KeyEventArgs e) 
{   
    if (e.KeyCode == Keys.A) 
    { 
     _timer.Start(); 
    } 
    if (e.KeyCode == "KEY_FOR_STOPPING_ANIMATION") 
    { 
     _timer.Stop(); 
    } 
} 

void timer1_Tick(object sender, EventArgs e) 
{ 
    MoveLeft(); 
} 
相關問題