如何防止标签在for循环中彼此重叠

时间:2019-07-08 15:47:56

标签: c# label

好的,所以我要从表单内的文本框中提取文本。我想从该文本内的每个字母创建一个带有其自己的字体大小和颜色的标签。问题是,当我在for循环中遍历创建标签的文本中的每个字母时,标签最终彼此叠加。结果只看到一个字母。

如何自动将标签彼此相邻放置,使其再次类似于普通文本,并防止其堆积?

我想为每个字母创建标签的原因是,在某个特定的位置,我希望字母分别移动。

class MyGroup: Control
    {
        string s;
        private Random rnd = new Random();

    public MyGroup()
    {
        this.AutoSize = true;
        this.Location = new System.Drawing.Point(10, 10);
        this.Name = "groupBox1";
        this.Size = new System.Drawing.Size(126, 21);
        this.TabIndex = 5;
        this.TabStop = false;
        //this.Text = "groupBox1";
    }

    public void SetString(string s)
    {
        this.s = s;
    }

    public void Fall()
    {
        for (int i = 0; i < s.Length; i++)
        {

            Label l = new Label
            {
                Location = new System.Drawing.Point(this.Location.X, this.Location.Y),
                ForeColor = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256)),
                Font = new Font("Arial", rnd.Next(7, 15), FontStyle.Bold)
            };
            l.Text += this.s[i];
            this.Parent.Controls.Add(l);
        }

        this.Visible = false;

    }
}

在Form.cs中:

private void button1_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(EnteredText.Text) && EnteredText.Text.Length > 1)
            {
                EnteredText.Text.ToCharArray();
                groupBox1.SetString(EnteredText.Text);
                groupBox1.Fall();


            }
        else
        {
            MessageBox.Show("Please enter a text with more than 2 letters.");
        }
    }

1 个答案:

答案 0 :(得分:0)

用以下内容替换“秋天”的正文:

int nextX =  this.Location.X;
for (int i = 0; i < s.Length; i++)
{
    Label l = new Label
    {
        Location = new System.Drawing.Point(nextX, this.Location.Y),
        ForeColor = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256)),
        Font = new Font("Arial", rnd.Next(7, 15), FontStyle.Bold),
    };
    l.Text += this.s[i];
    l.Width = TextRenderer.MeasureText(l.Text, l.Font).Width;
    this.Parent.Controls.Add(l);
    nextX += l.Width;
}

this.Visible = false;

它看起来像这样:
example