public partial class ImageMove : Form
{
public ImageMove()
{
InitializeComponent();
}
int x = 1;//x为1代表水平向右移动,-1代表水平向左移动
int y = 1;//y为1代表垂直向下移动,-1代表垂直向上移动
int move = 5;//每次移动的距离,水平和垂直都是一样的
private void timer1_Tick(object sender, EventArgs e)
{
//根据x值设置图片的位置
if (x == 1)
{
this.pictureBox1.Left += move;
}
else
{
this.pictureBox1.Left -= move;
}
//根据y值设置图片位置
if (y == 1)
{
this.pictureBox1.Top += move;
}
else
{
this.pictureBox1.Top -= move;
}
//水平方向
//撞到右边(减20主要是考虑到窗体有边框)
if(x==1&&this.pictureBox1.Left+this.pictureBox1.Width>=this.Width-20)
{
x = -1;
}
//撞到左边
else if (x == -1 && this.pictureBox1.Left <= 0)
{
x = 1;
}
//垂直方向
//撞到底端(37代表标题栏的高度)
if(y==1&&this.pictureBox1.Top+this.pictureBox1.Height>= this.Height-37)
{
y = -1;
}
//撞到顶端
else if(y==-1&&this.pictureBox1.Top <= 0)
{
y = 1;
}
}
}