因此,在我的项目中,我需要读取一个.txt文件,该文件由“。”和“#”组成。该.txt文件是迷宫的地图。#是不可逾越的对象,。是应能够收集的项目。
我已经设法解析文本并创建一个TableLayoutPanel
包含Label
控件的控件,其中包含#和.。但是,我想用位于单元格中心的圆圈替换.。
我该怎么做呢?这就是我所拥有的。
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;
}
创建a时,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
并访问其所有属性。请注意,Lambda
只要Label
需要绘制,即在您使它无效或其容器之一或系统需要刷新它时,都将调用上述内容。
然后它将始终使用当前数据,因此,当您以后更改文本时,它将使用新文本:
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
例如,当更改颜色时,您可以将它们存储在某个位置,并使用这些值来创建渐变画笔,而不是对其进行硬编码。
无论何时更改这些数据,你需要调用Invalidate
的Label
。Text
所做的更改将为您完成此操作,但其他数据需要您触发重新绘制。
还要注意,由于将“标签”设置为它们所在Dock.Fill
的单元格,因此您也可以在其中绘制圆圈:
ee.Graphics.DrawEllipse(Pens.Blue, 0, 0, l.Width - 1, l.Height - 1);
当然,我LinearGradientBrush
只是为了好玩插入了..
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句