2013-03-01 62 views
2

我有一个小问题,我想创建一个缓慢移动到墙上的标签,当它碰到墙壁时,它应该返回到另一面墙上。我将标签放在左边,但过了一段时间后它会通过窗体并消失,是否有可能在它碰到窗体时向右转(其他方向)?所以它从墙到墙?如何在贴在墙上时改变标签的方向?

public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
     timer1.Enabled = true; 

    } 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     label1.Left = label1.Left + 10; 
    } 
+0

你可以使用表格宽度为长城。当你的标签位置==表格宽度,然后递减位置10 – 2013-03-01 11:48:46

回答

1

你必须知道你有可用的宽度和标签文本的宽度,那么你可以创建一个说,一个条件,当currentPosition + labelWidth >= availableWidth然后将其他的方式。当然,屏幕左侧还会有类似的情况。

我的建议:

private int velocity = 10; 
private void timer1_Tick(object sender, EventArgs e) 
{ 

if (currentWidth + labelWidth >= availableWidth) 
    { 
     //set velocity to move left 
     velocity = -10; 
    } 
else if (currentWidth - labelWidth <= 0) 
    { 
     //set velocity to move right 
     velocity = 10; 
    } 
label1.Left = label1.Left + velocity; 

} 
1
Sounds like homework to me... just in case it isn't: 

private int direction = 1; 
private int speed = 10; 

public Form1() 
{ 
    InitializeComponent(); 
} 

private void Form1_Load(object sender, EventArgs e) 
{ 
    direction = 1; 
    timer1.Enabled = true; 

} 

private void timer1_Tick(object sender, EventArgs e) 
{ 
    if(label1.Left + label1.Width > this.Width && direction == 1){ 
     direction = -1; 
    } 
    if(label1.Left <= 0 && direction == -1){ 
     direction = 1; 
    } 
    label1.Left = label1.Left + (direction * speed); 
} 
+0

谢谢你!我被困了这么久,因为我真的需要这些代码! (我正在做一些大事!) – user2123343 2013-03-01 12:00:41

+1

您应该使用'ClientSize.Width',因为'Width'包含边框。另外:为什么不改变'速度'的标志? 'if(label1.Left <0 || label1.Left + label1.Width> ClientSize.Width)speed = -speed; label1.Left + = speed;' – pescolino 2013-03-01 12:16:00

+0

为'ClientSize.Width'注满了效果,我做了如此详细的解释性说明,并且如果标签宽度发生变化(从右边框向左增长),它可能会卡住。 。 – mindandmedia 2013-03-01 14:11:04