041集——封装之:新建图层(CAD—C#二次开发入门)

发布于:2025-02-24 ⋅ 阅读:(16) ⋅ 点赞:(0)

如图所示:增加一个图层“新图层”,颜色为红(1),当图层颜色定义为黄(2)时,直接覆盖之前图层颜色,图层名不变。

代码如下:

 

  /// </summary>
  /// <param name="数据库db"></param>
  /// <param name="图层名layname"></param>
  /// <param name="图层颜色colorindex"></param>
  /// <returns>图层名layname</returns>
  public static string AddLayer(this Database db, string layname, short colorindex)
  {
      if ((colorindex < 0) || (colorindex > 256))
      {
          colorindex = 0;
      };
      //var pt = Point3d.Origin;
      
      //Application.DocumentManager.MdiActiveDocument.Editor.GetPoint(out pt, "asdf");
      // 获得当前文档和数据库   Get the current document and database
      Document acDoc = Application.DocumentManager.MdiActiveDocument;
      //Database db = acDoc.Database;

      // 启动一个事务  Start a transaction
      using (Transaction acTrans = db.TransactionManager.StartTransaction())
      {
          // 以只读方式打开图层表   Open the Layer table for read
          LayerTable acLyrTbl;
          acLyrTbl = acTrans.GetObject(db.LayerTableId,
                                       OpenMode.ForRead) as LayerTable;

          if (acLyrTbl.Has(layname) == false)
          {
              LayerTableRecord acLyrTblRec = new LayerTableRecord();

              // Assign the layer the ACI color 1 and a name
              acLyrTblRec.Color = Color.FromColorIndex(ColorMethod.ByAci, colorindex);
              acLyrTblRec.Name = layname;
              // Upgrade the Layer table for write
              acLyrTbl.UpgradeOpen();

              // Append the new layer to the Layer table and the transaction
              acLyrTbl.Add(acLyrTblRec);
              acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
          }
          else//已存在图层名
          {
              ObjectId layerId = acLyrTbl[layname];
              LayerTableRecord layerRecord = acTrans.GetObject(layerId, OpenMode.ForRead) as LayerTableRecord;
              layerRecord.UpgradeOpen();
              layerRecord.Color = Color.FromColorIndex(ColorMethod.ByAci, colorindex);
             // acTrans.AddNewlyCreatedDBObject(layerRecord, true);
          }

           以只读方式打开块表   Open the Block table for read
          //BlockTable acBlkTbl;
          //acBlkTbl = acTrans.GetObject(db.BlockTableId,
          //                             OpenMode.ForRead) as BlockTable;

           以写方式打开模型空间块表记录   Open the Block table record Model space for write
          //BlockTableRecord acBlkTblRec;
          //acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
          //                                OpenMode.ForWrite) as BlockTableRecord;
          //Save the changes and dispose of the transaction
          acTrans.Commit();
      }
      return layname;
  }