【问题标题】:Getting points from a .txt file and plotting them in a picturebox in C#从 .txt 文件中获取点并将它们绘制在 C# 中的图片框中
【发布时间】:2015-07-07 21:25:05
【问题描述】:

我正在尝试构建一个 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);
    }

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

我使用的txt文件如下

0,4,0

1,2,1

2,1,2

3,6,3

4,1,4

5,3,5

6,8,6

【问题讨论】:

    标签: c# user-interface plot infinite-loop


    【解决方案1】:

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

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

    【讨论】:

    • 经过一番研究,使用图表工具不是更好吗?您能否解释一下如何使用该工具,因为我不知道,您可能会告诉我我刚刚开始编码。谢谢!任何代码表示赞赏
    • @AbdullahNawaz 我不知道你在说什么图表工具。
    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    • 2023-04-01
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多