如何使用 C# 代码在自定义 AutoCAD 2007 DXF 中创建一些带有顶点的折线?我想创建一个 DXF 供激光打标软件导入。
这是一些对我有用的原始 C#。它需要将相当大的 19KB 头文件复制到目标文件,然后将页脚文件附加到其中。
它会在每条折线的“5”标题属性下生成一个十六进制值。这是因为它需要每条折线有一个唯一的标识符。 我能够顺利地编写 1044 个多边形、99702 个顶点。最大的问题是标题,我没有努力简化它,所以大约有 2650 行。页脚有 34 行。
由于我无法上传页眉和页脚,您需要创建它们。我使用 LibreCAD 创建了 Basic Autocad 2007 DXF,并绘制了一条带有几个点的非闭合折线。使用 Notepad++,我在文件中搜索 LWPOLYLINE 以找到行位置,在该位置我可以确定头文件的结尾,就在“0”和“LWPOLYLINE”开始之前创建为 DXF_header.txt 文件,然后我可以制作DXF_footer.txt 文件位于折线的最后一个 Y 顶点坐标下方。
在文本编辑器中保存所有内容
并制作DXF_header.txt
页脚文件看起来像这样
确保在头文件末尾和页脚文件中也留下一个新行。代码如下。
public void WriteDXF(int num_rows)
{
string sourceheaderFile = @"c:\DDMG\DXF_header.txt";
string sourcefooterFile = @"c:\DDMG\DXF_footer.txt";
var start = DateTime.Now;
string OUTFILE = @"c:\DDMG\SAMPLE.dxf";
//delete if exists
DeleteFileIfExists(OUTFILE);
// Copy the header file and overwrite if it already exists
File.Copy(sourceheaderFile, OUTFILE, true);
Console.WriteLine($"WriteDXF: Writing dxf file '{OUTFILE}'..");
int verticeswritten = 0;
int polyswritten = 0;
int startHexValue = 0xA0; // Specify the starting hex value using an int
int step = 1; // How much to increment the hex value
// Increment the hex value
int nextHexValue = startHexValue + step;
// Convert the incremented value back to a hex string
string nextHexString = nextHexValue.ToString("X");
using (StreamWriter myfile = new StreamWriter(OUTFILE, true))
{
for (int n = 0; n < MainImageBlock.PolyLineIncrementedCount; n++)
{
myfile.WriteLine(" 0");
myfile.WriteLine("LWPOLYLINE");
myfile.WriteLine(" 5"); // Leading spaces for 3-digit group codes
myfile.WriteLine(nextHexValue.ToString("X"));
myfile.WriteLine("100");
myfile.WriteLine("AcDbEntity");
myfile.WriteLine(" 8");
myfile.WriteLine("0");
myfile.WriteLine(" 6");
myfile.WriteLine("ByLayer");
myfile.WriteLine(" 62");
myfile.WriteLine(" 256");
myfile.WriteLine("370");
myfile.WriteLine(" -1");
myfile.WriteLine("100");
myfile.WriteLine("AcDbPolyline");
myfile.WriteLine("90");
myfile.WriteLine(" " + MainImageBlock.Polylines[n].VertexCount);
myfile.WriteLine(" 70");
myfile.WriteLine(" 0");
myfile.WriteLine(" 43"); //scale factor
myfile.WriteLine("0");
//copy over all vertices from this imageblock
for (int i = 0; i < MainImageBlock.Polylines[n].VertexCount; i++)
{
myfile.WriteLine(" 10");
myfile.WriteLine(MainImageBlock.Polylines[n].X[i]);
myfile.WriteLine(" 20");
myfile.WriteLine(MainImageBlock.Polylines[n].Y[i]);
verticeswritten++;
}
step++;
nextHexValue = startHexValue + step;
polyswritten++;
}
}
// Read the contents of the source file
byte[] footerContents = File.ReadAllBytes(sourcefooterFile);
// Append the contents to the destination file
using (FileStream fs = new FileStream(OUTFILE, FileMode.Append))
{
fs.Write(footerContents, 0, footerContents.Length);
}
Console.WriteLine($"WriteDXF: written {polyswritten} polys, {verticeswritten} vertices.");
Console.WriteLine("WriteDXF: DXF creation complete!");
}