繁体   English   中英

当字符隐藏在左侧时,如何在右侧显示,如何将标签的文本从右向左移动?

[英]How to move label's text right to left,when a character hides in left it shows on right?

这是我的关键代码:

using System;
using System.Windows.Forms;
namespace Scroller
{
    public partial class Form1 : Form
    {
        int i, j;
        bool k = false;
        public Form1()
        {
            InitializeComponent();                                  
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label1.Text = "Time:"+ System.DateTime.Now.ToString();
            i--;
            j = i + this.Width;
            if (i < this.Width && i > 0)
            {
                label1.Left = i;
            }
            else
            if (i < 0 && k == false)
            {
                label1.Left = i;
                k = true;
            }
            else
            if (i < 0 && k == true)
            {
                label1.Left = j;
                k = false;
            }

            if (i < 0 - label1.Width)
            {
                i = this.Width - label1.Width;
            }
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            label1.Text = "Time:"+  System.DateTime.Now.ToString();
            i = this.Width - label1.Width;
            label1.Left = i;
        }
    }
}

我要做出的效果是整个时间字符串从右向左移动。 当文本的像素在左侧消失时(因为它不在表单的左边框内),该像素将显示在右侧。

换句话说,不能通过删除字符串的第一个字符并将其附加到最后一个字符来产生效果。

我知道使用两个标签来做会更容易。 在表单中设置自己的位置,并在表单旁边隐藏另一个。 同时移动它们。

当第一个标签到达表单的左边界时,第二个标签到达表单的右边界。 然后第一个移出,第二个移入。直到第二个完全移入,重置其x位置。

但我只想使用一个标签。 因此,我选择快速切换标签的位置,并尝试“欺骗”用户的眼睛。 问题是当标签在左右之间切换时,它会非常明显地闪烁。 即使我将计时器的间隔设置为20以下,问题仍然存在。

您能帮我解决闪烁问题还是启发我其他可以仅使用一个标签和一个计时器产生所需效果的方法?

谢谢。 如果我没有描述我的问题,或者我的问题不够清楚,或者需要更多代码,请告诉我。

我认为您无法解决在Windows窗体中更改标签位置的闪烁问题。

另一个解决方案是将标签宽度设置为与表单宽度相同的大小,使标签文本使用空格填充所有宽度,并使计时器始终获取最后一个字符并将其放在字符串的开头。

下面的示例代码。

private void timer1_Tick(object sender, EventArgs e)
{
    label1.Text = label1.Text.Substring(label1.Text.Length - 1) + label1.Text.Remove(label1.Text.Length - 1);
}

private void Form1_Load(object sender, EventArgs e)
{
    // The total spaces required to fill the form vary from form.width and the initial label.text.width
    // Width | Spaces
    //  177  |   13
    //  228  |   30
    //  297  |   53
    //  318  |   60

    // The spacesEnd = 60 work for a form with width 319
    int spacesBegin = 0, spacesEnd = 60;

    label1.Text = "Time:" + System.DateTime.Now.ToString();
    label1.AutoSize = false;
    label1.Left = -3;
    label1.Width = this.Width - 1;
    label1.Height = 15;
    label1.BorderStyle = BorderStyle.FixedSingle;

    for (int i = 0; i < spacesBegin; i++)
        label1.Text = " " + label1.Text;
    for (int i = 0; i < spacesEnd; i++)
        label1.Text += " ";

    Timer timer = new Timer();
    timer.Tick += timer1_Tick;
    timer.Interval = 50;
    timer.Start();
}

暂无
暂无

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

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