【发布时间】:2016-07-03 11:52:42
【问题描述】:
所以在我的项目中,我需要读取一个由“.”和“#”组成的 .txt 文件。这个 .txt 文件是迷宫的地图。 # 是不可通过的对象,而 . 是应该能够被收集的项目。
我已经设法解析文本并创建一个包含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;
}
【问题讨论】:
-
任何类似的事情都应该在 Paint 事件中完成,但是我强烈建议您使用 WPF 等图形更“友好”的环境而不是 WinForms
-
遗憾的是,在这种情况下我需要使用 winforms(任务说我必须这样做)。我尝试使用图形事件,但我不知道如何获取 .'s 的特定单元格的位置。你知道我怎样才能完成这项工作吗?
标签: c# winforms graphics io gdi+