C#开发AutoCAD插件:获取圆中心、Hatch属性及解决Area报错
AutoCAD C#插件:填充中心显示属性问题解决方案
问题1:获取圆的中心坐标
通过事务以只读模式打开选中的Circle对象,直接读取其Center属性即可:
// 打开选中的圆对象 var circle = tr.GetObject(id, OpenMode.ForRead) as Circle; if (circle == null) continue; // 获取圆心坐标 Point3d center = circle.Center;
问题2:正确获取Hatch属性及解决hatch.Area报错
hatch.Area报错的核心原因是:事务未提交前,刚创建的Hatch对象即使调用了EvaluateHatch(true),部分属性仍可能未完全初始化。针对圆填充的场景,直接使用圆本身的Area属性即可(填充面积与圆面积完全一致),既避免报错又保证数据准确。
完整修正后的代码
using Autodesk.AutoCAD.ApplicationServices; using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.EditorInput; using Autodesk.AutoCAD.Geometry; using Autodesk.AutoCAD.Runtime; public class HatchAreaTool { [CommandMethod("DisplayArea")] // 修正原命令名拼写错误:DisplyArea → DisplayArea public static void SelectCirclesToHatch() { var doc = Application.DocumentManager.MdiActiveDocument; var db = doc.Database; var ed = doc.Editor; // 筛选选择圆对象 var filter = new SelectionFilter(new[] { new TypedValue(0, "CIRCLE") }); var selection = ed.GetSelection(filter); if (selection.Status != PromptStatus.OK) return; using (var tr = db.TransactionManager.StartTransaction()) { var curSpace = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); foreach (var id in selection.Value.GetObjectIds()) { // 读取圆对象的核心属性 var circle = tr.GetObject(id, OpenMode.ForRead) as Circle; if (circle == null) continue; Point3d center = circle.Center; double area = circle.Area; // 创建并配置填充对象 var ids = new ObjectIdCollection(new[] { id }); using (var hatch = new Hatch()) { curSpace.AppendEntity(hatch); tr.AddNewlyCreatedDBObject(hatch, true); hatch.SetHatchPattern(HatchPatternType.PreDefined, "ANSI31"); hatch.Associative = true; hatch.AppendLoop(HatchLoopTypes.Outermost, ids); hatch.EvaluateHatch(true); } // 创建显示面积的文本对象 DBText acText = new DBText(); acText.Position = center; acText.TextString = $"填充面积: {area:F2}"; // 格式化显示两位小数 acText.Height = 0.5; acText.Justify = AttachmentPoint.MiddleCenter; // 文本中心对齐,避免偏移 curSpace.AppendEntity(acText); tr.AddNewlyCreatedDBObject(acText, true); } tr.Commit(); } } }
关键修正说明
- 修正了命令名的拼写错误,避免调用失败
- 添加圆对象读取逻辑,直接获取圆心坐标
- 改用圆的
Area属性替代Hatch的Area,彻底解决报错问题 - 给文本设置中心对齐,让面积文本精准显示在圆心位置
- 格式化面积数值为两位小数,提升可读性
内容的提问来源于stack exchange,提问作者Shahgee
相关产品推荐
相关产品推荐

