因此,在我的项目中,我需要读取一个由“.”和“#”组成的.txt 文件。此 .txt 文件是迷宫的 map 。 # 是无法通过的物体,. 是应该能够收集的元素。
我已经成功解析文本并创建一个包含 Label
控件的 TableLayoutPanel
,其中包含 # 和 .。不过,我想用单元格中心的圆圈替换 .。
我该怎么做? 这是我所拥有的。
public class Import: TableLayoutPanel
{
public int zeilen, spalten;
TableLayoutPanel tlp = new TableLayoutPanel();
public TableLayoutPanel getData(string path)
{
StreamReader sr;
TableLayoutPanel tlp = new TableLayoutPanel();
tlp.Dock = DockStyle.Fill;
tlp.CellBorderStyle = 0;
if (File.Exists(path))
{
try
{
using (sr = new StreamReader(path))
{
spalten = Int32.Parse(sr.ReadLine().Trim());
zeilen = Int32.Parse(sr.ReadLine().Trim());
TableLayoutColumnStyleCollection Columns = tlp.ColumnStyles;
TableLayoutRowStyleCollection Rows = tlp.RowStyles;
foreach (ColumnStyle Column in Columns)
tlp.ColumnStyles.Add((new ColumnStyle(SizeType.Percent, 100.0F / Convert.ToSingle(spalten))));
foreach (RowStyle Row in Rows)
tlp.RowStyles.Add((new RowStyle(SizeType.Percent, 100.0F / Convert.ToSingle(zeilen))));
for (int i = 1; i <= zeilen; i++)
{
string line = sr.ReadLine();
for (int j = 1; j <= spalten; j++)
{
Label l = new Label();
tlp.Controls.Add(l, j-1, i-1);
l.Dock = DockStyle.Fill;
l.Text = line.Substring(j-1, 1);
l.Name = "l" + i.ToString() + "r" + (j).ToString();
if (line.Substring(j - 1, 1) == "#")
l.ForeColor = Color.Green;
if (line.Substring(j - 1, 1) == ".")
{
l.ForeColor = Color.Blue;
Graphics g = l.CreateGraphics();
g.DrawEllipse(new Pen(Color.Blue), l.Location.X, l.Location.Y, tlp.Width, tlp.Height);
}
}
}
return tlp;
}
}
catch(Exception e) { MessageBox.Show(e.Message); MessageBox.Show(e.StackTrace); return null; }
}
else
return null;
}
最佳答案
创建 Label
时,您可以同时创建其 Paint
事件,内联为 Lambda
:
Label l = new Label();
l.Name = "Label #" + (i * zeilen).ToString("00") + ":" + j.ToString("00");
l.Text = "ABCE";
l.Paint += (ss, ee) =>
{
// do your painting here:
using (LinearGradientBrush lgb =
new LinearGradientBrush(l.ClientRectangle, Color.Cyan, Color.DarkCyan, 0f))
ee.Graphics.FillRectangle(lgb, l.ClientRectangle);
ee.Graphics.DrawString(l.Text, Font, Brushes.Black, 1, 1);
};
您可以将sender ss
转换为Label
并访问其所有属性。请注意,每当需要绘制Label
时,即每当您使其无效它或其容器之一或< strong>系统需要刷新的地方。
它将始终使用当前数据,因此当您稍后更改文本时,它将使用新文本:
Label oneOfMyLabels = tlp.Controls["Label #03:02"] as Label; // pick or find the right one!
if (oneOfMyLabels != null)
{
oneOfMyLabels.Text = "New Text";
oneOfMyLabels.Invalidate(); // optional when change the text of a Label
}
请注意,您始终需要在 Paint
事件的外部存储控制绘画的数据,无论是在类级别还是以某种方式绑定(bind)到控件。
例如,当更改颜色时,您可以将它们存储在某处并使用这些值来创建渐变画笔,而不是对它们进行硬编码。
每当您更改这些数据时,您都需要在 Label
上调用 Invalidate
。 Text
更改将为您完成此操作,但其他数据需要您触发重新绘制..!
另请注意,由于您将标签设置为Dock.Fill
,因此它们所在的单元格也可以在其中绘制圆圈:
ee.Graphics.DrawEllipse(Pens.Blue, 0, 0, l.Width - 1, l.Height - 1);
当然,我插入LinearGradientBrush
只是为了好玩..
关于c# - 如何在标签中创建图形对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38169669/