Cad通过外部文件数据绘图(x,y点)

该代码示例展示了如何读取文本文件中的坐标数据,将这些数据整理成多段线,然后将其添加到图形数据库中。程序首先读取指定路径的文件内容,将每一行的内容分割并存储到列表中,接着解析坐标数据并创建多段线对象,最后将多段线添加到模型空间。
摘要由CSDN通过智能技术生成

文件名

 string fileName = @"C:\桌面\坐标.txt";

把文件内容读取到数组

 string[] contents = File.ReadAllLines(fileName);

声明List对象 将数据进行整理

 List<List<string>> list = new List<List<string>>();
 for (int i = 0; i < contents.Length; i++)
 {
     string[] cont = contents[i].Split(new char[] { ' ' });
     List<string> subList = new List<string>();
     for (int j = 0; j < cont.Length; j++)
     {
         subList.Add(cont[j]);
     }
     list.Add(subList);
 }

声明多段线

Polyline pLine = new Polyline();

解析

for (int i = 0; i < list.Count; i++)
{
    //数据转换
    double X, Y;
    bool bx = double.TryParse(list[i][0],out X);
    bool by = double.TryParse(list[i][1],out Y);

    if (bx == false || by == false)
    {
        Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
        ed.WriteMessage("外部文件有错误,绘制图形失败!");
        return;
    }
    pLine.AddVertexAt(i, new Point2d(X, Y), 0, 0, 0);
}

添加到图形数据库

 Database db = HostApplicationServices.WorkingDatabase;
 db.AddEntityToModelSpace(pLine);

完整代码

        [CommandMethod("DrawDemo")]
        public void DrawDemo()
        {
            //Console.WriteLine("请输入路径:");
            //string p = Console.ReadLine();
            string fileName = @"E:\桌面\刚创建的文本.txt";
            string[] contents = File.ReadAllLines(fileName);
            List<List<String>> list = new List<List<string>>();
            for (int i = 0; i < contents.Length; i++)
            {
                string[] con = contents[i].Split(new char[] { ' ' });
                List<string> subList = new List<string>();
                for (int j = 0; j < con.Length; j++)
                {
                    subList.Add(con[j]);
                }
                list.Add(subList);
            }
            Polyline pLine = new Polyline();
            for (int i = 0; i < list.Count; i++)
            {
                double x, y;
                bool bx = double.TryParse(list[i][0],out x);
                bool by = double.TryParse(list[i][0], out y);
                if (bx == false || by == false)
                {
                    Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
                    ed.WriteMessage("绘制失败!!!");
                    return; 
                }
                pLine.AddVertexAt(i,new Point2d(x,y),0,0,0);
            }
            Database db = HostApplicationServices.WorkingDatabase;
            db.AddEntityToModelSpace(pLine);
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

周杰伦fans

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值