首页 > 解决方案 > 如何防止标签在 for 循环中相互重叠

问题描述

好的,所以我从表单内的文本框中获取文本。我想从该文本中的每个字母创建一个标签,具有自己的字体大小和颜色。问题是,当我对创建标签的文本中的每个字母进行 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.");
        }
    }

标签: c#label

解决方案


将“Fall”的主体替换为:

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;

它看起来像这样:
例子


推荐阅读