简体   繁体   English

C#从左到右移动标签

[英]C# Move a Label from left to right

i'm wondering is there any solution to animate a label with a timer? 我想知道是否有使用计时器为标签设置动画的解决方案? I want the label2 to go slowly to the left until is hitting the label1 and when it's hitted, to go backward from where has started going to the left. 我希望label2缓慢向左移动,直到碰到label1并被击中,然后从开始向左的位置向后退。 I tried this, but when is hitting label1 it's stopping: 我试过了,但是当碰到label1时,它就停止了:

       label2.Location = new Point(label2.Location.X - 4, label2.Location.Y);

        if (label2.Location.X == label1.Location.Y)
        {
            label2.Location = new Point(label2.Location.X + 4, label2.Location.Y);
        }

You are comparing label2.Location.X == label1.Location.Y , which seems like a typo. 您正在比较label2.Location.X == label1.Location.Y ,这似乎是一个错字。

You need a direction variable and you need to store the original position of Label2 so it knows where to go to: 您需要一个方向变量,并且需要存储Label2的原始位置,以便它知道要去哪里:

label2.Location = new Point(label2.Location.X + step, label2.Location.Y);
if (label2.Location.X <= label1.Location.X) {
  step = 4;
} else if (label2.Location.X >= originalX) {
  step = -4;
}

To setup your variables: 设置变量:

int step = -4;
int originalX;

and then use the Load override method to set the originalX value: 然后使用Load Override方法设置originalX值:

protected override void OnLoad(EventArgs e) {
  base.OnLoad(e);
  originalX = label2.Location.X;
}

I think you are moving always left. 我认为您总是向左移动。 Shouldn't you be using a variable to keep track of the direction you want to move. 您不应该使用变量来跟踪要移动的方向。

In that sense, you need to check when you've reached the right margin to change direction again. 从这种意义上讲,您需要检查何时到达正确的边距以再次更改方向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM