c# - 如何防止标签在 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.");
}
}
解决方案
将“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;
推荐阅读
- zip - zip' 或 'tar' 命令生成归档到标准输出
- php - php cronofy 集成不起作用。如何解决?
- git - 如何在 git 中合并 PR 后重新设置开发分支?
- angular - Angular 热敏打印不适用于 HTTP 而不是 HTTPS
- java - 如何在 Drools 文件中传递多个对象并提取所需的对象
- python - 从 Fortran 到 Python 的转换是傅里叶变换
- sql-server - SQL Server - updlock,可序列化不会阻止 100%
- c# - 在C#中使用内存流下载excel文件
- minio - 无法运行 Minio 客户端
- javascript - 如何在 Angular 9 中调用其他函数中的函数?