使用netdxf(C#)框架实现dxf文件读取与导出坐标

2024-01-13 04:28

本文主要是介绍使用netdxf(C#)框架实现dxf文件读取与导出坐标,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

使用netdxf(C#)框架实现dxf文件读取与导出坐标

一、新建窗体应用程序DxfToolDemo,将默认的Form1重命名为FormDxfTool

窗体FormDxfTool.Designer.cs设计器源程序如下:


namespace DxfToolDemo
{partial class FormDxfTool{/// <summary>/// 必需的设计器变量。/// </summary>private System.ComponentModel.IContainer components = null;/// <summary>/// 清理所有正在使用的资源。/// </summary>/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>protected override void Dispose(bool disposing){if (disposing && (components != null)){components.Dispose();}base.Dispose(disposing);}#region Windows 窗体设计器生成的代码/// <summary>/// 设计器支持所需的方法 - 不要修改/// 使用代码编辑器修改此方法的内容。/// </summary>private void InitializeComponent(){this.rtxtMessage = new System.Windows.Forms.RichTextBox();this.btnOpenDxf = new System.Windows.Forms.Button();this.btnExportCsv = new System.Windows.Forms.Button();this.SuspendLayout();// // rtxtMessage// this.rtxtMessage.Location = new System.Drawing.Point(12, 70);this.rtxtMessage.Name = "rtxtMessage";this.rtxtMessage.Size = new System.Drawing.Size(1102, 529);this.rtxtMessage.TabIndex = 0;this.rtxtMessage.Text = "";// // btnOpenDxf// this.btnOpenDxf.Font = new System.Drawing.Font("宋体", 15F);this.btnOpenDxf.Location = new System.Drawing.Point(23, 12);this.btnOpenDxf.Name = "btnOpenDxf";this.btnOpenDxf.Size = new System.Drawing.Size(127, 43);this.btnOpenDxf.TabIndex = 1;this.btnOpenDxf.Text = "打开Dxf文件";this.btnOpenDxf.UseVisualStyleBackColor = true;this.btnOpenDxf.Click += new System.EventHandler(this.btnOpenDxf_Click);// // btnExportCsv// this.btnExportCsv.Font = new System.Drawing.Font("宋体", 15F);this.btnExportCsv.Location = new System.Drawing.Point(185, 12);this.btnExportCsv.Name = "btnExportCsv";this.btnExportCsv.Size = new System.Drawing.Size(182, 43);this.btnExportCsv.TabIndex = 2;this.btnExportCsv.Text = "导出坐标为.CSV";this.btnExportCsv.UseVisualStyleBackColor = true;this.btnExportCsv.Click += new System.EventHandler(this.btnExportCsv_Click);// // FormDxfTool// this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;this.ClientSize = new System.Drawing.Size(1126, 611);this.Controls.Add(this.btnExportCsv);this.Controls.Add(this.btnOpenDxf);this.Controls.Add(this.rtxtMessage);this.Name = "FormDxfTool";this.Text = "Dxf转化工具【CAD文件转坐标】";this.Load += new System.EventHandler(this.FormDxfTool_Load);this.ResumeLayout(false);}#endregionprivate System.Windows.Forms.RichTextBox rtxtMessage;private System.Windows.Forms.Button btnOpenDxf;private System.Windows.Forms.Button btnExportCsv;}
}

二、右键 项目DxfToolDemo, 管理NuGet程序包,输入关键字netDxf,下载该程序包

三、netDxf框架关键类型说明:

关键结构 netDxf.Vector3
            可以认为是立体三维坐标(x,y,z)
关键结构 netDxf.Vector2
            可以认为是平面二维坐标(x,y)

DxfDocument用于读写dxf文件

      关键函数Load()用于加载文件

      添加实体:dxfDocument.Entities.Add(EntityObject entity);

      关键函数Save()用于保存文件 

关键属性:
Entities:

对应类型 netDxf.Collections.DrawingEntities

密封类DrawingEntities由一系列【点、线、圆等】集合组成,允许直接访问与图形中实体相关的操作

对应的各种实体EntityObject说明:
netDxf.Entities.EntityObject:
        Gets the complete list entities contained in the active layout.
        抽象类,以下所有实体对象的父类

netDxf.Entities.PolyfaceMesh:
    Represents a polyface mesh entity.

netDxf.Entities.Text:
    Gets the list of texts in the active layout.
           
 netDxf.Entities.MText:       
     Gets the list of multiline texts in the active layout.

 netDxf.Entities.Hatch:       
     Gets the list of hatches in the active layout.

 netDxf.Entities.Image:     
     Gets the list of images in the active layout.
 
netDxf.Entities.Mesh:      
        Gets the list of mesh in the active layout.
 
netDxf.Entities.Leader:        
        Gets the list of leader in the active layout.
             
netDxf.Entities.Point:
        Gets the list of points in the active layout.
        
netDxf.Entities.Tolerance:
        Gets the list of tolerance in the active layout.
        
netDxf.Entities.MLine:
        Gets the list of multilines in the active layout.
        
netDxf.Entities.Dimension:
        Gets the list of dimensions in the active layout.
        
netDxf.Entities.Spline:
        Gets the list of splines in the active layout.
         
netDxf.Entities.Ray:
        Gets the list of rays in the active layout.

netDxf.Entities.Viewport:        
        Gets the list of viewports in the active layout.

netDxf.Entities.XLine:
        Gets the list of extension lines in the active layout.
        
netDxf.Entities.Underlay:
        Gets the list of underlay in the active layout.
       
netDxf.Entities.PolygonMesh:
        Gets the list of polygon meshes in the active layout.

netDxf.Entities.AttributeDefinition:
        Gets the list of attribute definitions in the active layout.

netDxf.Entities.Polyline3D:
        Gets the list of polylines in the active layout.

netDxf.Entities.Arc:
        Gets the list of arcs contained in the active layout. 

netDxf.Entities.Ellipse:
        Gets the list of ellipses in the active layout.

netDxf.Entities.Wipeout:
        Gets the list of wipeouts in the active layout. 

netDxf.Entities.Face3D:
        Gets the list of 3d faces in the active layout.

netDxf.Entities.Circle:
        Gets the list of circles in the active layout.

netDxf.Entities.Trace:
        Gets the list of traces in the active layout.

netDxf.Entities.Insert:
        Gets the list of inserts in the active layout.

netDxf.Entities.Line:
        Gets the list of lines in the active layout.

netDxf.Entities.Shape:
        Gets the list of shapes in the active layout.

netDxf.Entities.Polyline2D:
        Gets the list of polylines in the active layout.

netDxf.Entities.Solid:
        Gets the list of solids in the active layout.

四、新建csv导出类CsvUtil,

CsvUtil.cs源程序如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace DxfToolDemo
{public class CsvUtil{/// <summary>/// 写CSV日志 按列显示/// </summary>/// <param name="fileName"></param>/// <param name="coordList">元组:圆心坐标,半径,模板名</param>/// <returns></returns>public static bool WriteCoordinateLogCsv(string fileName, List<Tuple<netDxf.Vector3, double, string>> coordList){if (coordList == null || coordList.Count == 0) {return false;}try{string directoryPath = Path.GetDirectoryName(fileName);if (!Directory.Exists(directoryPath)){Directory.CreateDirectory(directoryPath);}string columnContents = "模板名,极柱序号,圆心X坐标,圆心Y坐标,圆心Z坐标,圆心半径\r\n";if (!File.Exists(fileName)){File.AppendAllText(fileName, columnContents, Encoding.Default);}StringBuilder sb = new StringBuilder();using (StreamWriter write = new StreamWriter(fileName, true, Encoding.Default)){for (int i = 0; i < coordList.Count; i++){sb = new StringBuilder();sb.Append($"{ProcessPunctuationForCsv(coordList[i].Item3)},");sb.Append($"{i + 1},");sb.Append($"{coordList[i].Item1.X},");sb.Append($"{coordList[i].Item1.Y},");sb.Append($"{coordList[i].Item1.Z},");sb.Append($"{coordList[i].Item2}");write.WriteLine(sb.ToString());}                    }return true;}catch (Exception ex){System.Windows.Forms.MessageBox.Show("CSV文件写入失败:" + ex.Message);return false;}}/// <summary>/// 处理csv文件中的双引号和逗号,使其在Excel中完美显示为一个单元格/// 斯内科/// </summary>/// <param name="srcStr"></param>/// <returns></returns>private static string ProcessPunctuationForCsv(string srcStr){if (srcStr == null){return string.Empty;}bool quoteFlag = false;//是否添加过双引号//如果存在双引号,需要将字符串的一个双引号 替换为 两个双引号。并且需要在字符串的前后加上双引号if (srcStr.Contains("\"")){srcStr = srcStr.Replace("\"", "\"\"");srcStr = "\"" + srcStr + "\"";quoteFlag = true;}//如果只存在逗号(不存在引号),将前后加引号即可if (srcStr.Contains(",") && !quoteFlag){srcStr = "\"" + srcStr + "\"";}return srcStr;}}
}

五、窗体程序如下:

FormDxfTool.cs源程序:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;using netDxf;
using netDxf.Collections;
using netDxf.Entities;namespace DxfToolDemo
{public partial class FormDxfTool : Form{public FormDxfTool(){InitializeComponent();rtxtMessage.ReadOnly = true;            }/// <summary>/// 显示推送消息/// </summary>/// <param name="msg"></param>private void DisplayMessage(string msg){this.BeginInvoke(new Action(() =>{if (rtxtMessage.TextLength > 20480){rtxtMessage.Clear(); }rtxtMessage.AppendText($"{DateTime.Now.ToString("HH:mm:ss.fff")}->{msg}\n");rtxtMessage.ScrollToCaret();}));}private void btnOpenDxf_Click(object sender, EventArgs e){rtxtMessage.Clear();OpenFileDialog openFileDialog = new OpenFileDialog();openFileDialog.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;openFileDialog.Filter = "dxf|*.dxf|All|*.*";DialogResult dialog = openFileDialog.ShowDialog();if (dialog != DialogResult.OK){return;}string fileName = openFileDialog.FileName;//AppDomain.CurrentDomain.BaseDirectory + "testFile\\蓝本-CAD.dxf"DisplayMessage($"CAD文件dxf路径为【{fileName}】");DxfDocument dxfDocument = DxfDocument.Load(fileName);DisplayMessage($"活动布局的名称为【{dxfDocument.Entities.ActiveLayout}】");rtxtMessage.Tag = dxfDocument.Entities;IEnumerable<Circle> circles = dxfDocument.Entities.Circles;int circleCount = circles.Count();DisplayMessage($"读取到圆Circle的个数为【{circleCount}】");for (int i = 0; i < circleCount; i++){Circle circle = circles.ElementAt(i);DisplayMessage($"\x20\x20圆【{(i + 1).ToString("D3")}】,圆心坐标【({circle.Center})】,半径【{circle.Radius}】");}            }private void btnExportCsv_Click(object sender, EventArgs e){DrawingEntities drawingEntities = rtxtMessage.Tag as DrawingEntities;if (drawingEntities == null) {return;}List<Tuple<Vector3, double, string>> coordList = new List<Tuple<Vector3, double, string>>();IEnumerable<Circle> circles = drawingEntities.Circles;int circleCount = circles.Count();//找出所有的圆for (int i = 0; i < circleCount; i++){Circle circle = circles.ElementAt(i);//元组:圆心坐标,半径,活动设计名coordList.Add(Tuple.Create(circle.Center, circle.Radius, drawingEntities.ActiveLayout));}string fileName = AppDomain.CurrentDomain.BaseDirectory + "testFile\\蓝本.csv";bool result = CsvUtil.WriteCoordinateLogCsv(fileName, coordList);MessageBox.Show($"导出csv文件结果【{result}】\n路径:{fileName}");}private void FormDxfTool_Load(object sender, EventArgs e){/** 1、读取dxf文件的思路
新建DxfDocument对象-调用Load方法读取对应地址的dxf文件并保存在新建的DxfDocument对象中-从新建的DxfDocument对象中读取对应的元素
读取dxf文件:
DxfDocument dxf = DxfDocument.Load("蓝本.dxf");关键结构 netDxf.Vector3可以认为是立体三维坐标(x,y,z)
关键结构 netDxf.Vector2可以认为是平面二维坐标(x,y)读取文件中的核心属性:
Entities:
对应类型 netDxf.Collections.DrawingEntities密封类DrawingEntities由一系列【点、线、圆等】集合组成,允许直接访问与图形中实体相关的操作
netDxf.Entities.EntityObject:Gets the complete list entities contained in the active layout.抽象类,以下所有实体对象的父类netDxf.Entities.PolyfaceMesh:Represents a polyface mesh entity.netDxf.Entities.Text:Gets the list of texts in the active layout.netDxf.Entities.MText:       Gets the list of multiline texts in the active layout.netDxf.Entities.Hatch:       Gets the list of hatches in the active layout.netDxf.Entities.Image:     Gets the list of images in the active layout.netDxf.Entities.Mesh:      Gets the list of mesh in the active layout.netDxf.Entities.Leader:        Gets the list of leader in the active layout.netDxf.Entities.Point:Gets the list of points in the active layout.netDxf.Entities.Tolerance:Gets the list of tolerance in the active layout.netDxf.Entities.MLine:Gets the list of multilines in the active layout.netDxf.Entities.Dimension:Gets the list of dimensions in the active layout.netDxf.Entities.Spline:Gets the list of splines in the active layout.netDxf.Entities.Ray:Gets the list of rays in the active layout.netDxf.Entities.Viewport:        Gets the list of viewports in the active layout.netDxf.Entities.XLine:Gets the list of extension lines in the active layout.netDxf.Entities.Underlay:Gets the list of underlay in the active layout.netDxf.Entities.PolygonMesh:Gets the list of polygon meshes in the active layout.netDxf.Entities.AttributeDefinition:Gets the list of attribute definitions in the active layout.netDxf.Entities.Polyline3D:Gets the list of polylines in the active layout.netDxf.Entities.Arc:Gets the list of arcs contained in the active layout. netDxf.Entities.Ellipse:Gets the list of ellipses in the active layout.netDxf.Entities.Wipeout:Gets the list of wipeouts in the active layout. netDxf.Entities.Face3D:Gets the list of 3d faces in the active layout.netDxf.Entities.Circle:Gets the list of circles in the active layout.netDxf.Entities.Trace:Gets the list of traces in the active layout.netDxf.Entities.Insert:Gets the list of inserts in the active layout.netDxf.Entities.Line:Gets the list of lines in the active layout.netDxf.Entities.Shape:Gets the list of shapes in the active layout.netDxf.Entities.Polyline2D:Gets the list of polylines in the active layout.netDxf.Entities.Solid:Gets the list of solids in the active layout.            */}}
}

六、运行效果如图:

【获取所有半径为3的圆极柱】

导出csv

 

这篇关于使用netdxf(C#)框架实现dxf文件读取与导出坐标的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/600243

相关文章

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数

Makefile简明使用教程

文章目录 规则makefile文件的基本语法:加在命令前的特殊符号:.PHONY伪目标: Makefilev1 直观写法v2 加上中间过程v3 伪目标v4 变量 make 选项-f-n-C Make 是一种流行的构建工具,常用于将源代码转换成可执行文件或者其他形式的输出文件(如库文件、文档等)。Make 可以自动化地执行编译、链接等一系列操作。 规则 makefile文件

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

2. c#从不同cs的文件调用函数

1.文件目录如下: 2. Program.cs文件的主函数如下 using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using System.Windows.Forms;namespace datasAnalysis{internal static

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time