AutoCAD .Net 创建多段线Polyline

来源:互联网 发布:java疯狂讲义 pdf 编辑:程序博客网 时间:2024/05/23 15:04

以下代码展示:
往模型空间中添加一条多段线Polyline。多段线有三个顶点,分别为(0, 0) (100, 100) (100, 0)。
设置多段线的图层、颜色、线型、线宽请参考文章AutoCAD .Net 创建直线Line

using Autodesk.AutoCAD.Runtime;using Autodesk.AutoCAD.ApplicationServices;using Autodesk.AutoCAD.DatabaseServices;using Autodesk.AutoCAD.Geometry;using Autodesk.AutoCAD.EditorInput;using Autodesk.AutoCAD.Colors;[CommandMethod("NewPolyline")]public static void NewPolyline(){    Document doc = Application.DocumentManager.MdiActiveDocument;    Database db = doc.Database;    using (Transaction tr = db.TransactionManager.StartTransaction())    {        //-------------------------------        // 获取模型空间        //-------------------------------        BlockTable blockTbl = tr.GetObject(            db.BlockTableId, OpenMode.ForRead) as BlockTable;        BlockTableRecord modelSpace = tr.GetObject(            blockTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;        //-------------------------------        // 创建多段线        //-------------------------------        Polyline polyline = new Polyline();        polyline.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0);        polyline.AddVertexAt(1, new Point2d(100, 100), 0, 0, 0);        polyline.AddVertexAt(2, new Point2d(100, 0), 0, 0, 0);        //polyline.Closed = true;        //-------------------------------        // 添加到模型空间并提交到数据库        //-------------------------------        modelSpace.AppendEntity(polyline);        tr.AddNewlyCreatedDBObject(polyline, true);        tr.Commit();    }}

如果设置 Polyline.Closed 为 true,则多段线首尾自动闭合。

当往多段线中添加顶点时,多段线对象内部是动态分配内存的。所以,如果知道多段线的顶点数,可以在构造的时候指定以预先分配指定大小的内存。
public Polyline(int vertices);
以上代码可以更改为:

Polyline polyline = new Polyline(3);polyline.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0);polyline.AddVertexAt(1, new Point2d(100, 100), 0, 0, 0);polyline.AddVertexAt(2, new Point2d(100, 0), 0, 0, 0);

当顶点数量很大时,这种方法会提升程序的性能。
注意:vertices 并没有指定多段线的顶点数,只是预先分配了存储 vertices 个顶点数据的内存。

当多段线对象不断地通过 AddVertexAt 增加顶点或者 RemoveVertexAt 减少顶点时,内部的动态内存只会不断增加。当代码完成增加或减少顶点时,有可能存在未被使用的动态内存,为了释放这部分未使用的内存,请在最后使用 Polyline.MinimizeMemory()。