将在图表控件上绘制的点写入文本文件,但每个坐标只能写入一次
本文关键字:坐标 一次 文件 控件 绘制 文本 | 更新日期: 2023-09-27 17:49:18
按钮点击事件:
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是List
drawPoints是我在chart1 paint事件中使用的List:
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>
的推荐方法。点是Serializeable
,所以这几行就可以保存和加载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
。