用户界面-从.txt文件中获取点,并在c#的图片框中绘制它们

本文关键字:绘制 txt 文件 获取 用户界面 并在 | 更新日期: 2023-09-27 18:01:32

我试图构建一个windows窗体应用程序,其中我从.txt文件中读取逗号分隔的列表,然后使用DrawLine函数绘制。我的代码一直陷入无限循环,我不确定我应该如何继续下去。我对如何绘制它没有偏好,我使用drawline函数的唯一原因是因为我不知道任何其他方法,所以我愿意接受任何其他可能更适合完成这项任务的想法。

       private void startToolStripMenuItem_Click(object sender, EventArgs e)
    {
        StreamReader sr = new StreamReader("../../sample.txt");
        string[] values = null;
        zee1 = sr.ReadLine();
        while (zee1 != null)
        {
            values = zee1.Split(',');
            x1 = Int32.Parse(values[0]);
            x2 = Int32.Parse(values[1]);
            y1 = Int32.Parse(values[2]);
        }

        //BackGroundBitmap.Save("result.jpg"); //test if ok
        Point point1 = new Point(int.Parse(values[0]), int.Parse(values[2]));
        Point point2 = new Point(int.Parse(values[1]), int.Parse(values[2]));
        pictureBox1.Enabled = true;
        g = pictureBox1.CreateGraphics();
        g.DrawLine(pen1, point1, point2);
    }

请注意,我试图在相同的图上绘制两个不同的x值,对应相同的y值。此外,values[0]是一个数组,包含.txt文件的第一列中的所有数据,等等值[1]和值[2]。

我使用的txt文件如下

0 4 0

1、2、1

2 1 2

3、6、3

4, 1、4

5、3、5

6 8 6

用户界面-从.txt文件中获取点,并在c#的图片框中绘制它们

您处于无限while循环中,因为条件永远不会改变。需要更新zee1。最流行的方法是简单地在中更新它条件:

while ((zee1 = sr.ReadLine()) != null)
{
    // what was here already
}

似乎你也想画一组线段(我假设一个到下一个),所以你可以这样做:

private void startToolStripMenuItem_Click(object sender, EventArgs e)
{
    List<Point> points = new List<Point>();
    using (StreamReader sr = new StreamReader("../../sample.txt"))
    {
        string[] values = null;
        while ((zee1 = sr.ReadLine()) != null)
        {
            values = zee1.Split(',');
            points.Add(new Point(int.Parse(values[0]), int.Parse(values[2])));
        }
    }
    pictureBox1.Enabled = true;
    g = pictureBox1.CreateGraphics();
    for (int i = 0; i < points.Count - 1; i++)
        g.DrawLine(pen1, points[i], points[i+1]);
}