Skip to main content
 首页 » 编程设计

C# 从左到右移动标签

2024年02月13日11grandyang

我想知道是否有任何解决方案可以使用计时器为标签制作动画?我希望 label2 缓慢向左移动,直到碰到 label1 并且当它被击中时,从开始向左移动的位置向后移动。 我试过了,但是当点击 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); 
        } 

请您参考如下方法:

您正在比较 label2.Location.X == label1.Location.Y,这似乎是一个拼写错误。

您需要一个方向变量并且需要存储 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; 
} 

设置变量:

int step = -4; 
int originalX; 

然后使用Load override方法设置originalX值:

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