将在图表控件上绘制的点写入文本文件,但每个坐标只写一次?

Write points drawn over a chart control to a text file the but only once each coordinate?

在按钮点击事件中:

private void chart1_MouseClick(object sender, MouseEventArgs e)
{
    if (outofrange == false)
    {
        valuePoints.Add(new PointF(X, Y));
        paintToCalaculate = true;

        if (X > 0 && Y > 0)
        {
            chart1.Invalidate();
            SavePointsCoordinates();
        }
    }
}

以及 SavePointsCoordinates 方法:

StreamWriter w;
int countPoints = 0;

private void SavePointsCoordinates()
{
    if (drawPoints.Count > 0)
    {
        foreach (Point p in drawPoints)
        {
            countPoints++;
            w = new StreamWriter(@"c:\chart\chartData.txt",true);
            w.WriteLine("Point " + countPoints + "X = " + p.X + " Y = " + p.Y);
        }

        w.Close();
    }
}

问题是,如果我在不添加新点的情况下多次单击按钮,它将继续向文本文件添加相同的坐标。

实际上,它已将相同的点坐标添加到按钮单击事件中的 valuePoints。 valuePoints 是列表

drawPoints 是我在 chart1 绘画事件中使用的列表:

Pen pen = new Pen(Color.Blue, 2.5f);
SolidBrush myBrush = new SolidBrush(Color.Red);

private void chart1_Paint(object sender, PaintEventArgs e)
{
    if (paintToCalaculate)
    {
        Series s = chart1.Series.FindByName("dummy");

        if (s == null)
        {
            s = chart1.Series.Add("dummy");
        }

        drawPoints.Clear();
        s.Points.Clear();

        foreach (PointF p in valuePoints)
        {
            s.Points.AddXY(p.X, p.Y);
            DataPoint pt = s.Points[0];
            double x = chart1.ChartAreas[0].AxisX.ValueToPixelPosition(pt.XValue);
            double y = chart1.ChartAreas[0].AxisY.ValueToPixelPosition(pt.YValues[0]);
            drawPoints.Add(new Point((int)x, (int)y));
            s.Points.Clear();
        }

        paintToCalaculate = false;
        chart1.Series.Remove(s);
    }

    foreach (Point p in drawPoints)
    {
        e.Graphics.FillEllipse(Brushes.Red, p.X - 2, p.Y - 2, 4, 4);
    }

    if (drawPoints.Count > 1)
    {
        e.Graphics.DrawLines(pen, drawPoints.ToArray());
    }
}

我想做的是将我在图表上绘制的所有点坐标写入一个文本文件,然后在构造函数中读回文本文件,将点绘制回图表并绘制线条他们之间。

我不确定我画的点和线之间的顺序是否有意义。只是为了将所有坐标写入文本文件并读回。

这里是推荐的保存方式List<Point>PointSerializeable,所以这几行将用于保存和加载 List<Point> points:

string yourPointsFile = "d:\myPoints.xml";
XmlSerializer xmls = new XmlSerializer(typeof(List<Point>));

// save the points maybe when closing the program:
using (Stream writer = new FileStream(yourPointsFile, FileMode.Create))
{
    xmls.Serialize(writer, points);
    writer.Close();
}

// load the points at startup:

using (Stream reader = new FileStream(yourPointsFile, FileMode.Open))
{
    points = xmls.Deserialize(reader);
    reader.Close();
}

收集正确的点数,添加或不添加它们是另一个问题。为避免重复,您始终可以使用

if (!points.Contains(somePoint) ) points.Add(somePoint);

保存和加载的点列表将具有相同的顺序。因此,如果要使用它们来绘制线条,顺序确实很重要,则生成的线条应该相同。

我认为每次点击都保存点数没有意义,但这是您的程序。也许在关闭程序时保存它们就足够了..?

如果您像您一样想要保存 PointF,只需将对 Point 的两个引用更改为 PointF