2011-01-28 176 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

太谢谢你了... –