首页 > 解决方案 > 如何在表单上移动图片框,以便当它到达表单末尾时它会循环回到另一侧?

问题描述

我已经完成了从左到右的操作,并且在到达表单末尾后它成功返回到起始位置,这是我的代码:

pictureBox1.Left +=10;

if (pictureBox1.Left >= this.Width )
{
    pictureBox1.Left = 0 - pictureBox1.Width; //Move the picturebox goes to start again

    ...                
}

现在我的问题是,如果 PictureBox 从右到左,我该怎么做?我知道我将制作的代码pictureBox1.Left +=10pictureBox1.Left -=10但我怎样才能让它在它的起始位置重新开始呢?

标签: c#

解决方案


您可以尝试另一个for循环:

如何循环图片框向左无限

像这样:

  // we start at pictureBox1.Left (which is initial position) with step = 10 
  // no condition (infinite loop)
  // move to the right 
  for (int left = pictureBox1.Left, initial = pictureBox1.Left, step = 10; ; left += step) {
    // If we beoynd [0 - step..Width + step] range, we
    //   1. Go to initial position
    //   2. Reverse direction 
    if (left >= Width + step && left <= -step) {
      left = initial;
      step = -step;
    }

    pictureBox1.Left = left;
  }

推荐阅读