1、建立一個圖形對象的步驟如下
(1)得到建立對象的圖形資料庫;
(2)在記憶體中建立實體類的一個對象;
(3)定義一個指向目前資料庫的事務處理;
(4)打開圖形資料庫的塊表;
(5)打開一個存儲實體的塊表記錄(通常繪圖都在模型空間中進行),所有模型空間的實體都存儲在塊表“模型空間”記錄中;
(6)将該對象添加到塊表記錄中;
(7)把對象添加到事務進行中;
(8)送出事務處理。
2、添加直線的例子
using System;
using System.Collections;
using System.Collections.Specialized;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using AutoCAD;
[assembly: CommandClass(typeof(YunyouXueYuan.MyCommands))]
namespace YunyouXueYuan
{
public class MyCommands
{
[CommandMethod("MKLine")]
public void MKLine()
{
//(1)擷取目前活動圖形資料庫
Database db = HostApplicationServices.WorkingDatabase;
//(2)建立一個直線對象
Point3d startPoint = new Point3d(0, 100, 0); //直線起點
Point3d endPoint = new Point3d(100, 100, 0); //直線終點
Line line = new Line(startPoint, endPoint);
//(3)定義一個指向目前資料庫的事務處理,以添加直線
using (Transaction trans = db.TransactionManager.StartTransaction())
{
//(3-1)以讀方式打開塊表..
BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
//(3-2)以寫方式打開模型空間塊表記錄
BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
//(3-3)将圖形對象的資訊添加到塊表記錄中,并傳回ObjectId對象.
btr.AppendEntity(line);
//(3-4)把對象添加到事務進行中.
trans.AddNewlyCreatedDBObject(line, true);
//(3-5)送出事務處理
trans.Commit();
}
}
}
3、例子代碼結構截圖
這個例子非常簡單,想學習AutoCAD二次開發(c#、C++等語言)、BIM軟體二次開發、Java、python等線上課程的同學,請關注雲幽學院的視訊課程 yunyou.ke.qq.com。
想擷取例子完整源代碼的同學,yunyou.ke.qq.com報名免費課程加群即可。