????????Teigha是一款專為開發者設計的工具,其核心技術在于強大的API和豐富的功能集,提供了一系列工具和方法,使開發者能夠輕松地讀取、解析和操作DWG文件。它支持多種操作系統,能在處理大型DWG文件時保持高效性能,還可用于構建數據轉換工具,將DWG文件轉換為其他格式,或進行反向轉換。
????????此外,Teigha能與BIM軟件集成,支持DWG文件的導入和導出,提升BIM模型的數據兼容性。眾多CAD軟件替代品,如Bricscad、ZWCAD和IntelliCAD等,也都依賴Teigha來處理DWG格式和與Acad對象進行交互。
Teigha簡介
Teigha是Bentley公司提供的CAD文件格式開發庫,允許開發者在不依賴AutoCAD的情況下讀寫DWG/DXF文件。與AutoCAD .NET API相比,Teigha具有跨平臺特性,支持多種開發語言和操作系統。
?
核心命名空間
?
- ?Bentley.MicroStation.DgnPlatformNET?:基礎平臺功能
?
- ?Bentley.DgnPlatformNET?:DGN文件操作
?
- ?Bentley.DwgPlatformNET?:DWG文件操作
?
- ?Bentley.GeometryNET?:幾何圖形處理
?
- ?Bentley.MathNET?:數學計算功能
?
基本功能示例與代碼
?
下面通過幾個典型場景演示Teigha在C#中的基本應用,包括文件讀寫、圖形創建、對象遍歷和屬性操作:
using System;
using System.Collections.Generic;
using Bentley.DwgPlatformNET;
using Bentley.DgnPlatformNET;
using Bentley.GeometryNET;
using Bentley.MathNET;
using Bentley.Transactions;namespace TeighaCADExample
{class Program{static void Main(string[] args){// 初始化Teigha平臺InitializeTeigha();try{// 1. 創建新DWG文件并添加圖形CreateNewDWGFile();// 2. 讀取DWG文件并遍歷對象ReadAndProcessDWGFile();// 3. 修改現有圖形對象屬性ModifyEntityProperties();// 4. 執行圖形集合運算PerformGeometryOperations();Console.WriteLine("Teigha示例執行完成!");}catch (Exception ex){Console.WriteLine($"錯誤: {ex.Message}");}finally{// 清理資源CleanUpTeigha();}Console.ReadKey();}// 初始化Teigha平臺static void InitializeTeigha(){// 加載Teigha許可證License BentleyLicense = new License();BentleyLicense.SetProductLevel(License.ProductLevels.Professional);Console.WriteLine("Teigha平臺初始化成功");}// 清理Teigha資源static void CleanUpTeigha(){// 釋放許可證等資源Console.WriteLine("Teigha資源已清理");}// 示例1:創建新DWG文件并添加圖形static void CreateNewDWGFile(){string filePath = @"C:\Temp\TeighaExample.dwg";// 創建DWG文檔using (DwgDocument doc = new DwgDocument()){// 開始事務using (Transaction tr = doc.TransactionManager.StartTransaction()){// 獲取模型空間BlockTableRecord modelSpace = doc.Database.ActiveModelSpace;// 1. 添加直線LineString line = new LineString();line.StartPoint = new Point3d(0, 0, 0);line.EndPoint = new Point3d(10, 0, 0);// 創建DwgLine實體DwgLine dwgLine = new DwgLine();dwgLine.Geometry = line;// 添加到模型空間modelSpace.AppendEntity(dwgLine);tr.AddNewlyCreatedDBObject(dwgLine, true);Console.WriteLine("已添加直線");// 2. 添加圓Circle circle = new Circle();circle.Center = new Point3d(5, 5, 0);circle.Radius = 3.0;DwgCircle dwgCircle = new DwgCircle();dwgCircle.Geometry = circle;modelSpace.AppendEntity(dwgCircle);tr.AddNewlyCreatedDBObject(dwgCircle, true);Console.WriteLine("已添加圓");// 3. 添加文本TextElement text = new TextElement();text.Text = "Teigha示例文本";text.Position = new Point3d(5, 0, 0);text.Height = 1.0;DwgText dwgText = new DwgText();dwgText.Geometry = text;modelSpace.AppendEntity(dwgText);tr.AddNewlyCreatedDBObject(dwgText, true);Console.WriteLine("已添加文本");// 提交事務并保存文件tr.Commit();doc.SaveAs(filePath);Console.WriteLine($"文件已保存至: {filePath}");}}}// 示例2:讀取DWG文件并遍歷對象static void ReadAndProcessDWGFile(){string filePath = @"C:\Temp\TeighaExample.dwg";if (!System.IO.File.Exists(filePath)){Console.WriteLine("示例文件不存在,請先執行創建文件操作");return;}using (DwgDocument doc = new DwgDocument()){// 打開DWG文件doc.Open(filePath);Console.WriteLine("已打開DWG文件");using (Transaction tr = doc.TransactionManager.StartTransaction()){// 獲取模型空間BlockTableRecord modelSpace = doc.Database.ActiveModelSpace;Console.WriteLine("開始遍歷模型空間對象:");int entityCount = 0;// 遍歷模型空間所有實體foreach (DBObject obj in modelSpace){if (obj is Entity entity){entityCount++;// 根據實體類型執行不同操作if (entity is DwgLine line){LineString lineGeom = line.Geometry as LineString;Console.WriteLine($"發現直線: 起點({lineGeom.StartPoint.X},{lineGeom.StartPoint.Y}), 終點({lineGeom.EndPoint.X},{lineGeom.EndPoint.Y})");}else if (entity is DwgCircle circle){Circle circleGeom = circle.Geometry as Circle;Console.WriteLine($"發現圓: 圓心({circleGeom.Center.X},{circleGeom.Center.Y}), 半徑{circleGeom.Radius}");}else if (entity is DwgText text){TextElement textGeom = text.Geometry as TextElement;Console.WriteLine($"發現文本: \"{textGeom.Text}\", 位置({textGeom.Position.X},{textGeom.Position.Y})");}}}Console.WriteLine($"共找到{entityCount}個圖形實體");tr.Commit();}}}// 示例3:修改現有圖形對象屬性static void ModifyEntityProperties(){string filePath = @"C:\Temp\TeighaExample.dwg";if (!System.IO.File.Exists(filePath)){Console.WriteLine("示例文件不存在,請先執行創建文件操作");return;}using (DwgDocument doc = new DwgDocument()){doc.Open(filePath);using (Transaction tr = doc.TransactionManager.StartTransaction()){BlockTableRecord modelSpace = doc.Database.ActiveModelSpace;Console.WriteLine("開始修改對象屬性:");int modifiedCount = 0;foreach (DBObject obj in modelSpace){if (obj is Entity entity){// 1. 修改顏色:將所有對象設為紅色entity.Color = Color.FromColorIndex(ColorMethod.ByAci, 1); // 紅色// 2. 特別處理圓:增大半徑if (entity is DwgCircle circle){Circle circleGeom = circle.Geometry as Circle;circleGeom.Radius *= 1.5;circle.Geometry = circleGeom;Console.WriteLine($"圓半徑已修改為{circleGeom.Radius}");modifiedCount++;}// 3. 特別處理文本:修改內容else if (entity is DwgText text){TextElement textGeom = text.Geometry as TextElement;textGeom.Text = "修改后的Teigha示例文本";text.Geometry = textGeom;Console.WriteLine("文本內容已修改");modifiedCount++;}}}if (modifiedCount > 0){Console.WriteLine($"成功修改{modifiedCount}個對象屬性");tr.Commit();doc.Save();}else{Console.WriteLine("未找到可修改的對象");}}}}// 示例4:執行圖形集合運算static void PerformGeometryOperations(){// 創建新文件用于演示幾何運算string filePath = @"C:\Temp\TeighaGeometry.dwg";using (DwgDocument doc = new DwgDocument()){using (Transaction tr = doc.TransactionManager.StartTransaction()){BlockTableRecord modelSpace = doc.Database.ActiveModelSpace;// 1. 創建兩個相交的圓用于求交運算Circle circle1 = new Circle();circle1.Center = new Point3d(5, 5, 0);circle1.Radius = 3.0;DwgCircle circleEnt1 = new DwgCircle();circleEnt1.Geometry = circle1;modelSpace.AppendEntity(circleEnt1);tr.AddNewlyCreatedDBObject(circleEnt1, true);Circle circle2 = new Circle();circle2.Center = new Point3d(8, 5, 0);circle2.Radius = 3.0;DwgCircle circleEnt2 = new DwgCircle();circleEnt2.Geometry = circle2;modelSpace.AppendEntity(circleEnt2);tr.AddNewlyCreatedDBObject(circleEnt2, true);// 2. 執行幾何求交運算GeometryIntersector intersector = new GeometryIntersector();GeometryBase result = intersector.GetIntersection(circle1, circle2);if (result is Point3dCollection intersectionPoints){Console.WriteLine($"兩圓相交,找到{intersectionPoints.Count}個交點");// 將交點繪制成點foreach (Point3d pt in intersectionPoints){PointElement point = new PointElement();point.Position = pt;DwgPoint pointEnt = new DwgPoint();pointEnt.Geometry = point;modelSpace.AppendEntity(pointEnt);tr.AddNewlyCreatedDBObject(pointEnt, true);}}else{Console.WriteLine("兩圓未相交");}// 3. 創建矩形和圓形用于求差運算Polyline polyline = new Polyline();polyline.AddVertexAt(0, new Point3d(2, 2, 0), 0, 0, 0);polyline.AddVertexAt(1, new Point3d(2, 8, 0), 0, 0, 0);polyline.AddVertexAt(2, new Point3d(8, 8, 0), 0, 0, 0);polyline.AddVertexAt(3, new Point3d(8, 2, 0), 0, 0, 0);polyline.Closed = true;DwgPolyline rectEnt = new DwgPolyline();rectEnt.Geometry = polyline;modelSpace.AppendEntity(rectEnt);tr.AddNewlyCreatedDBObject(rectEnt, true);// 執行矩形減去圓形的差集運算GeometryDifferencer differencer = new GeometryDifferencer();GeometryBase diffResult = differencer.GetDifference(polyline, circle1);if (diffResult is Polyline resultPolyline){Console.WriteLine("成功執行差集運算");// 繪制差集結果DwgPolyline diffEnt = new DwgPolyline();diffEnt.Geometry = resultPolyline;diffEnt.Color = Color.FromColorIndex(ColorMethod.ByAci, 2); // 綠色modelSpace.AppendEntity(diffEnt);tr.AddNewlyCreatedDBObject(diffEnt, true);}tr.Commit();doc.SaveAs(filePath);Console.WriteLine($"幾何運算結果已保存至: {filePath}");}}}}
}
? ? ? ? ? ? ? ? ? ??
?
1. 基礎文件操作
?
- 文件創建:通過?DwgDocument?類創建新DWG文件,使用?Transaction?管理數據庫事務
?
- 文件讀取:通過?doc.Open()?方法讀取現有DWG文件,遍歷?ActiveModelSpace?中的實體
?
2. 圖形對象操作
?
- 直線創建:通過?LineString?定義線段起點和終點,封裝為?DwgLine?實體
?
- 圓形創建:使用?Circle?幾何對象定義圓心和半徑,轉換為?DwgCircle?
?
- 文本創建:通過?TextElement?設置文本內容、位置和高度,生成?DwgText?實體
?
3. 對象屬性修改
?
- 顏色修改:通過?entity.Color?屬性設置對象顏色(示例中使用紅色Aci 1)
?
- 幾何修改:直接操作幾何對象(如圓的半徑、文本內容)并更新實體
?
4. 幾何運算應用
?
- 求交運算:使用?GeometryIntersector?計算兩圓交點,結果為?Point3dCollection?
?
- 差集運算:通過?GeometryDifferencer?實現矩形與圓形的差集計算,返回新的多邊形
?
Teigha與AutoCAD API的主要差異
?
5.?架構設計:
?
- Teigha采用更通用的對象模型,不依賴AutoCAD環境
?
- AutoCAD API緊密綁定AutoCAD進程,需在AutoCAD中運行
?
6.?命名空間差異:
?
- Teigha使用?Bentley?命名空間(如?Bentley.DwgPlatformNET?)
?
- AutoCAD API使用?Autodesk.AutoCAD?命名空間
?
7.?幾何處理:
?
- Teigha提供獨立的?GeometryNET?命名空間,幾何運算功能更豐富
?
- AutoCAD API的幾何處理與實體對象耦合更緊密
?
8.?事務管理:
?
- 兩者都使用事務機制管理數據庫操作,但Teigha的?Transaction?接口更簡潔
?
開發環境配置
?
3.?引用程序集:
?
- 需要在項目中引用以下Teigha程序集:
?
- Bentley.DgnPlatformNET.dll
?
- Bentley.DwgPlatformNET.dll
?
- Bentley.GeometryNET.dll
?
- Bentley.MathNET.dll
?
- Bentley.Transactions.dll
?
4.?許可證管理:
?
- 使用Teigha前需初始化許可證(如示例中的?License?類)
?
- 商業應用需購買Bentley官方許可證
?
應用場景擴展
?
5.?批量文件處理:利用Teigha不依賴AutoCAD的特性,開發批量轉換、檢查DWG文件的工具
?
6.?跨平臺應用:基于Teigha的跨平臺能力,開發Windows、Linux或macOS環境下的CAD文件處理程序
?
7.?輕量化顯示:提取DWG文件中的幾何數據,用于輕量化圖形顯示或Web端可視化
?
8.?數據提取與分析:從DWG文件中提取特定類型的對象(如管道、結構構件)進行數據分析
?
上述示例代碼可直接編譯運行(需正確配置Teigha環境),實際項目中可根據需求進一步擴展功能,如添加圖層管理、塊參照處理、尺寸標注操作等高級功能。
以下是關于 **Teigha (Open Design Alliance SDK)** 在CAD二次開發中的基本應用示例,包含常見功能的詳細代碼和注釋。Teigha 是用于處理DWG/DXF文件的跨平臺開發庫,支持無需AutoCAD環境即可操作CAD文件。
一、Teigha開發環境準備**
1. 安裝Teigha SDK(ODA SDK)
2. 在C#項目中添加以下引用:
? ?- `Teigha.Core.dll`
? ?- `Teigha.Runtime.dll`
? ?- `Teigha.DatabaseServices.dll`
? ?- `Teigha.Geometry.dll`
二、基本功能示例**#### **1. 創建新DWG文件并添加直線**
?
using Teigha.Core;
using Teigha.DatabaseServices;
using Teigha.Geometry;
using System;public class TeighaBasicDemo
{public static void CreateDwgWithLine(){// 初始化Teigha環境Services.Start();?try{// 創建內存中的新Database(相當于DWG文件)using (Database db = new Database(true, true))using (Transaction tr = db.TransactionManager.StartTransaction()){// 打開塊表(BlockTable)BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;// 打開模型空間塊表記錄BlockTableRecord modelSpace = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;// 創建一條直線(從點(0,0,0)到點(100,100,0))Line line = new Line(new Point3d(0, 0, 0),new Point3d(100, 100, 0));// 將直線添加到模型空間modelSpace.AppendEntity(line);tr.AddNewlyCreatedDBObject(line, true);// 保存為DWG文件db.SaveAs("C:\\Temp\\Output.dwg", DwgVersion.Current);tr.Commit();}}catch (Exception ex){Console.WriteLine("Error: " + ex.Message);}finally{// 釋放Teigha資源Services.Release();}}
}
2. 讀取DWG文件并遍歷所有實體**
?
using Teigha.Core;
using Teigha.DatabaseServices;public class TeighaReadDemo
{public static void ReadDwgEntities(){Services.Start();try{using (Database db = new Database(false, true)){// 讀取現有DWG文件db.ReadDwgFile("C:\\Temp\\Sample.dwg", FileOpenMode.OpenForReadAndAllShare, false, null);using (Transaction tr = db.TransactionManager.StartTransaction()){BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;BlockTableRecord modelSpace = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;// 遍歷模型空間中的實體foreach (ObjectId entityId in modelSpace){Entity entity = tr.GetObject(entityId, OpenMode.ForRead) as Entity;if (entity != null){// 輸出實體類型和句柄Console.WriteLine($"Entity Type: {entity.GetType().Name}, Handle: {entity.Handle}");}}tr.Commit();}}}catch (Exception ex){Console.WriteLine("Error: " + ex.Message);}finally{Services.Release();}}
}
3. 創建圖層并設置顏色**
?
using Teigha.Core;
using Teigha.DatabaseServices;public class LayerDemo
{public static void CreateLayer(){Services.Start();try{using (Database db = new Database(true, true))using (Transaction tr = db.TransactionManager.StartTransaction()){// 獲取層表(LayerTable)LayerTable lt = tr.GetObject(db.LayerTableId, OpenMode.ForWrite) as LayerTable;// 創建新圖層LayerTableRecord layer = new LayerTableRecord{Name = "MyLayer",Color = Color.FromColorIndex(ColorMethod.ByAci, 1) // 紅色};// 將圖層添加到層表lt.Add(layer);tr.AddNewlyCreatedDBObject(layer, true);tr.Commit();db.SaveAs("C:\\Temp\\LayerDemo.dwg", DwgVersion.Current);}}catch (Exception ex){Console.WriteLine("Error: " + ex.Message);}finally{Services.Release();}}
}
4. 添加塊定義與塊引用
?
using Teigha.Core;
using Teigha.DatabaseServices;public class BlockDemo
{public static void CreateBlockWithReference(){Services.Start();try{using (Database db = new Database(true, true))using (Transaction tr = db.TransactionManager.StartTransaction()){// 創建塊定義BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;BlockTableRecord blockDef = new BlockTableRecord{Name = "MyBlock"};// 在塊定義中添加一個圓Circle circle = new Circle(new Point3d(0, 0, 0),Vector3d.ZAxis,50.0);blockDef.AppendEntity(circle);tr.AddNewlyCreatedDBObject(circle, true);// 將塊定義添加到塊表bt.Add(blockDef);tr.AddNewlyCreatedDBObject(blockDef, true);// 在模型空間中插入塊引用BlockTableRecord modelSpace = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;BlockReference blockRef = new BlockReference(new Point3d(200, 200, 0),blockDef.ObjectId);modelSpace.AppendEntity(blockRef);tr.AddNewlyCreatedDBObject(blockRef, true);tr.Commit();db.SaveAs("C:\\Temp\\BlockDemo.dwg", DwgVersion.Current);}}catch (Exception ex){Console.WriteLine("Error: " + ex.Message);}finally{Services.Release();}}
}
三、關鍵技術點說明**
1. **環境初始化與釋放** ?
? ?- `Services.Start()`:初始化Teigha運行時環境
? ?- `Services.Release()`:釋放資源(必須調用,否則內存泄漏)
2. **數據庫操作** ?
? ?- `new Database(true, true)`:創建空數據庫(第一個參數為`true`表示新建)
? ?- `db.ReadDwgFile()`:讀取現有DWG文件
? ?- `db.SaveAs()`:保存DWG文件
3. **事務管理** ?
? ?- 所有數據庫操作必須包裹在事務中
? ?- 使用`TransactionManager.StartTransaction()`開啟事務
? ?- 必須調用`Commit()`或`Abort()`結束事務
4. **實體操作流程** ?
? ?```plaintext
? ?創建實體 → 打開目標塊表記錄 → AppendEntity → AddNewlyCreatedDBObject
? ?```
四、Teigha與AutoCAD API的區別
| 功能? ? ? ? ? ? ? ? ?| Teigha (ODA)? ? ? ? ? ? ? ? ? ? ? ? ?? | AutoCAD .NET API ? ? ? ? ?|
|---------------------|----------------------------? ? ? ? ? ? ? ? |---------------------------|
| 環境依賴 ? ? ? ? ? ?| 無需安裝AutoCAD? ? ? ? ? ? ? ? ?| 必須安裝AutoCAD ? ? ? ? ? |
| 跨平臺支持 ? ? ? ? | 支持Windows/Linux/macOS? | 僅Windows ? ? ? ? ? ? ? ? |
| 文件格式支持 ? ? | 支持DWG/DXF/DWF? ? ? ? ? ? ?| 主要支持DWG ? ? ? ? ? ? ? |
| 類名前綴 ? ? ? ? ? ?| 無命名空間前綴(如`Database`)| 帶`Autodesk.AutoCAD`前綴 |
| 商業授權 ? ? ? ? ? ?| 需要ODA商業許可? ? ? ? ? ? ? ? ? ? | 需AutoCAD授權 ? ? ? ? ? ? |
五、常見問題處理
1. **句柄(Handle)沖突** ?
? ?使用`db.Undo()`回滾操作時需注意對象狀態管理。
2. **內存泄漏** ?
? ?確保所有`DBObject`在使用后調用`Dispose()`或包裹在`using`語句中。
3. **坐標系差異** ?
? ?Teigha使用右手坐標系,需注意與AutoCAD坐標系的一致性。
---
通過上述示例,可以快速掌握Teigha在CAD文件操作中的核心功能。建議參考ODA官方文檔([Open Design Alliance](https://www.opendesign.com/))獲取更詳細的API說明。