添加图形的工具事务类
public partial class addEntityTool { /// <summary> /// 将图形添加到文件中 /// </summary> /// <param name="db">图形数据库</param> /// <param name="ent">图形对象</param> /// <returns>图形的ObjectId</returns> public static ObjectId addEntityToolModelSpace(Database db, Entity ent ) { //声明ObjectID ,用于返回 ObjectId entId = ObjectId.Null; //开启事务处理 using (Transaction tran = db.TransactionManager.StartTransaction()) { //打开块表 BlockTable bt = (BlockTable)tran.GetObject(db.BlockTableId, OpenMode.ForRead); //打开块表记录 BlockTableRecord btr = (BlockTableRecord)tran.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); //添加图形到块表记录 entId = btr.AppendEntity(ent); //更新数据信息 tran.AddNewlyCreatedDBObject(ent, true); //提交事务 tran.Commit(); } return entId; } }
实现画直线的类
public class LineExam { [CommandMethod("LineDemo")] public void LineDemo() { Database db = HostApplicationServices.WorkingDatabase; Line line1 = new Line(new Point3d(100, 100, 0), new Point3d(200, 200, 0)); //使用addEntityTool这个类 addEntityTool.addEntityToolModelSpace(db, line1); } }
扩展:画多条直线,把图形的参数变ent成可变参数
/// <summary> /// 将图形添加到文件中 /// </summary> /// <param name="db">图形数据库</param> /// <param name="ent">图形对象,可变参数</param> /// <returns>图形的ObjectId,数组图层</returns> public static ObjectId addEntityToolModelSpace(this Database db, params Entity[] ent) { //声明ObjectID[] ,用于返回 ObjectId[] entId = new ObjectId[ent.Length]; //开启事务处理 using (Transaction tran = db.TransactionManager.StartTransaction()) { //打开块表 BlockTable bt = (BlockTable)tran.GetObject(db.BlockTableId, OpenMode.ForRead); //打开块表记录 BlockTableRecord btr = (BlockTableRecord)tran.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); for (int i = 0; i < ent.Length; i++) { //添加图形到块表记录 entId[i] = btr.AppendEntity(ent[i]); //更新数据信息 tran.AddNewlyCreatedDBObject(ent[i], true); } //提交事务 tran.Commit(); } return entId[ent.Length-1]; }
画线
Line line2 = new Line(new Point3d(100, 100, 0), new Point3d(200, 200, 0)); Line line3 = new Line(new Point3d(200, 100, 0), new Point3d(200, 800, 0)); Line line4 = new Line(new Point3d(300, 300, 0), new Point3d(500, 220, 0)); Line line5 = new Line(new Point3d(1000, 105, 0), new Point3d(300, 700, 0)); Line line6 = new Line(new Point3d(1003, 100, 0), new Point3d(200, 400, 0)); db.addEntityToolModelSpace(line1, line2, line3, line4, line5, line6);