txt文件如下
1
1,1
2,18
3,16
END
2
3,1
4,19
END
END
以上代表两条线,ID为1的线由(1,1)(2,18)(3,16)相连,以END为结束,ID为2的线由(3,1)(4,19)相连,以END为结束,读取完毕以END结束
要求在c#窗体程序中绘制txt文件中所表示的线段。
界面是一个panel和一个打开文件的按钮,在panel里绘制线段
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace huixian
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
#region Panel的重绘事件(防止在窗体切换时原来绘制的线段丢失)
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void panel1_Paint(object sender, PaintEventArgs e)
{
if (!string.IsNullOrEmpty(tbxFilePath.Text))
{
paintLine();
}
}
#endregion
#region 打开文件按钮事件处理
private void btnOpen_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "文本文件(*.txt)|*.txt";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
tbxFilePath.Text = openFileDialog1.FileName;
paintLine();
}
}
#endregion
#region 读取文件内容并绘制线段
private void paintLine()
{
Graphics gp = mainPanel.CreateGraphics();
Point p = new Point();
List<Point> pointList = new List<Point>();
string[] datas = File.ReadAllLines(openFileDialog1.FileName);
foreach (string str in datas)
{
if (str.Contains("END"))
{
for (int i = pointList.Count - 1; i >= 0; i--)
{
if (i >= 1)
{
gp.DrawLine(new Pen(Color.Red), pointList[i], pointList[i - 1]);
}
}
pointList.Clear();
}
else if (str.Contains(','))
{
string[] strs = str.Split(',');
p.X = Convert.ToInt32(strs[0]);
p.Y = Convert.ToInt32(strs[1]);
pointList.Add(p);
}
}
gp.Dispose();
}
#endregion
}
}