如何在标签中创建图形对象

时间:2016-07-03 11:52:43

标签: c# winforms graphics io gdi+

所以在我的项目中,我需要阅读一个.txt文件,其中包含"。"""#"' s。这个.txt文件是迷宫的地图。 #是无法通过的对象,而且。应该是可以收集的项目。

我已经设法在文本中解析并创建了一个包含TableLayoutPanel控件的Label,其中包含#和。' s。但是,我想用在单元格中居的圆圈替换。“

我该怎么做? 这就是我所拥有的。

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;
    }

2 个答案:

答案 0 :(得分:2)

创建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,只要无效它或其中一个容器,或系统< / 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事件的外部,无论是在类级别还是以某种方式绑定到控制。

例如,在更改颜色时,您会将它们存储在某处并使用这些值来创建渐变画笔而不是硬编码。

每当您更改这些数据时,您需要在Invalidate上致电LabelText更改将为您执行此操作,但其他数据需要才能触发重新绘制..!

另请注意,由于标签设置为Dock.Fill 单元格,因此您可以在那里绘制圆圈:

 ee.Graphics.DrawEllipse(Pens.Blue, 0, 0, l.Width - 1, l.Height - 1);

我当然只是为了好玩而插入LinearGradientBrush

答案 1 :(得分:0)

使用表单中的Paint事件:
https://msdn.microsoft.com/en-us/library/system.windows.forms.control.paint(v=vs.110).aspx 你可以在那里画一切。从矩形,圆形,字符串等....

using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
  public partial class Form1 : Form
  {
    private readonly Pen greenPen = new Pen(Brushes.Green);
    private readonly Pen redPen = new Pen(Brushes.Red);
    private readonly Font testFont = new Font(FontFamily.GenericSansSerif, 10f);

    public Form1()
    {
      InitializeComponent();
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
      e.Graphics.DrawRectangle(redPen, 0f, 0f, 100f, 100f);
      e.Graphics.DrawEllipse(greenPen, 10f, 10f, 200f, 200f);
      e.Graphics.DrawString("Hello Graphics", testFont, Brushes.Blue, 30f, 30f);
    }
  }
}