2011-01-28 104 views
3

我想將一個小圖像加載到WinForms pictureBox控件中,然後將它移動到移動到窗體的另一側。在C#中移動圖像

我已經加載圖像,並使用計時器來移動圖像,但是當我運行它時,應用程序只顯示pictureBox及其圖像的最終位置。

我如何才能平滑過渡到最終位置?

這裏是我到目前爲止的代碼:

public partial class Form1 : Form 
{ 
    private int counter = 0; 

    void timer_Tick(object sender, EventArgs e) 
    { 
     counter++; 
     if (counter == 1) 
     { 
      pictureBox1.Show(); 
      timer1.Stop(); 
      counter = 0; 
     } 
    } 

    public Form1() 
    { 
     InitializeComponent(); 

     timer1.Interval = 10; 
     timer1.Tick += new EventHandler(timer_Tick); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 

     while(i<=100){ 

      int x = pictureBox1.Location.X; 
      int y = pictureBox1.Location.Y; 

      pictureBox1.Location = new Point(x+25, y); 
      timer1.Start(); 
     } 
    } 
} 
+2

'while(i <= 100){'Where is'i' defined?根據所提供的代碼,您的循環永遠不會終止。 – Amy

回答

3

工作的呢?對不起,我無法測試它現在的位置(在沒有VS的上網本上)。

public partial class Form1 : Form 
{ 
    void timer_Tick(object sender, EventArgs e) 
    { 
     int x = pictureBox1.Location.X; 
     int y = pictureBox1.Location.Y; 

     pictureBox1.Location = new Point(x+25, y); 

     if (x > this.Width) 
      timer1.Stop(); 
    } 

    public Form1() 
    { 
     InitializeComponent(); 

     timer1.Interval = 10; 
     timer1.Tick += new EventHandler(timer_Tick); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     pictureBox1.Show(); 
     timer1.Start(); 
    } 
} 
+0

是的,它的工作...非常感謝yodaj007!但還有一件事:我可以降低運動圖像的速度嗎?! –

+1

當然,通過減少像素數量(而不是+25,使用+15)或增加間隔(而不是10,使用20)。或者這兩個。 – quip

+0

太謝謝你了... –