圖案填充的創建和其他實體,比如塊、文字樣式和標注樣式有所不同,需區別對待,單大致的方法和步驟都基本相同,只有個別地方不同。要創建 Hatch 對象,首先使用該類的構造函數創建一個空的填充對象,然后對該對象的類型、樣式、名稱、填充角度以及邊界等進行屬性設置。步驟如下

1、 創建圖案邊界:
利用創建圓命令創建一個填充邊界
Circle circle = New Circle(); circle.SetDatabaseDefaults();//用來把圓的顏色、圖層、線型、打印樣式、可見性等屬性設為實體所在的數據庫的默認值 circle.Center = new Point3d(3, 3, 0); circle.Radius = 1;
2、 創建圖案填充對象:
Hactch hatch =New Hatch();
3、 設置Hatch對象的屬性:
Hacth.PatternScale=0.5;
4、 設置填充的類型和填充圖案名稱:
hatch.SetDatabaseDefaults(); hatch.SetHatchPattern(HatchPatternType.PreDefined, "ANSI31");
HatchPatternType屬性說明:
HatchPatternType.PreDefined
從 acad.pat 文件中定義的圖案名中進行選擇。
HatchPatternType.UserDefined
用當前線型定義直線圖案。
HatchPatternType.CustomDefined
從 PAT 而不是 acad.pat 文件中選擇圖案名。
填充類型說明:
ANSI31:為金屬剖面線
其他如下圖


5、 設置關聯:
hatch.Associative = true;
6、 添加填充邊界:
acHatch.AppendLoop(HatchLoopTypes.Outermost, ids);//ids這里為ObjectID集
說明:添加的第一個邊界必須是外邊界,即用於定義圖案填充最外面的邊界。要添加外部邊界,請使用添加環的類型為 HatchLoopTypes.Outermost 常量的 AppendLoop 方法,一旦外邊界被定義,就可以繼續添加另外的邊界。添加內部邊界請使用帶 HatchLoopTypes.Default 常量的 AppendLoop 方法。
7、 計算並顯示填充:
hatch.EvaluateHatch(true);
8、 提交事務處理:
trans.Commit();
完整代碼:
1 using Autodesk.AutoCAD.Runtime; 2 3 using Autodesk.AutoCAD.ApplicationServices; 4 5 using Autodesk.AutoCAD.DatabaseServices; 6 7 using Autodesk.AutoCAD.Geometry; 8 9 10 11 [CommandMethod("AddHatch")] 12 13 public static void AddHatch() 14 15 { 16 17 // 獲得當前文檔和數據庫 18 19 Document acDoc = Application.DocumentManager.MdiActiveDocument; 20 21 Database acCurDb = acDoc.Database; 22 23 24 25 // 啟動一個事務 26 27 using (Transaction trans = acCurDb.TransactionManager.StartTransaction()) 28 29 { 30 31 // 以只讀方式打開塊表 32 33 BlockTable acBlkTbl; 34 35 acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, 36 37 OpenMode.ForRead) as BlockTable; 38 39 40 41 // 以寫方式打開模型空間塊表記錄 42 43 BlockTableRecord acBlkTblRec; 44 45 acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], 46 47 OpenMode.ForWrite) as BlockTableRecord; 48 49 50 51 // 創建一個圓對象作為圖案填充的封閉邊界 52 53 Circle circle = new Circle();//初始化Circle類 54 55 circle.SetDatabaseDefaults();//默認參數 56 57 circle.Center = new Point3d();//圓心位置 58 59 circle.Radius = 1;//圓的半徑 60 61 62 63 // 添加新的圓對象到塊表記錄和事務中 64 65 acBlkTblRec.AppendEntity(circle); 66 67 acTrans.AddNewlyCreatedDBObject(circle, true); 68 69 70 71 // 添加圓到一個 ObjectID 數組中去 72 73 ObjectIdCollection acObjIdColl = new ObjectIdCollection(); 74 75 acObjIdColl.Add(circle.ObjectId); 76 77 78 79 // 創建圖案填充對象並添加到塊表記錄中 80 81 Hatch hatch = new Hatch(); 82 83 acBlkTblRec.AppendEntity(hatch); 84 85 acTrans.AddNewlyCreatedDBObject(hatch, true); 86 87 88 89 hatch.SetDatabaseDefaults(); 90 91 hatch.SetHatchPattern(HatchPatternType.PreDefined, "ANSI31");//ANSI31為金屬剖面線 92 93 hatch.Associative = true; 94 95 hatch.AppendLoop(HatchLoopTypes.Outermost, acObjIdColl); 96 97 hatch.EvaluateHatch(true); 98 99 100 101 // 保存新對象到數據庫中 102 103 trans.Commit(); 104 105 } 106 107 }
