第九期视频回放

点击查看【bilibili】

第九期代码及课件下载地址

代码及课件下载地址

第九期直播内容文字版

本次直播内容主要是对实际生产过程中经常出现的需求进行案例的介绍。从内容上分,主要涉及两个部分,分别为:出图阶段的表格,图纸生成案例与事件驱动的参数化建模案例。
Slide2.JPG
图1 本期内容一览

出图相关案例

  1. 针对目前的设计生产模式来说,最终工程信息都会以图纸的形式进行表达。作为BIM模型,其中拥有海量的工程信息,但是如何将模型中的信息归类,快速整合并输出为符合公司出图标准的图纸或表格,也是目前BIM技术短时间无法取代传统CAD绘制出图模式的一大原因。这里,我们给大家分别介绍用于生成符合公司要求图表的工具Demo和绘制构件后自动生成图纸的工具Demo

表格生成工具

  1. 该工具主要用于从模型中提取生成表格所需的信息,并自动生成表格。对于表格本身,若表格较为简单,可使用MicroStation内置的表格,若内置表格样式无法满足出图的需要,那么可以采用线与文字配合生成的方式,创建符合公司出图标准的图表,同时,表格数据还可输出为Excel文件的格式,提供多样形式的数据输出。

需求说明:
使用工具对构件进行筛选,选择完毕后从选择的元素中提取生成图表的有效信息生成图表,同时也可使用表格信息生成对应的Excel文件。
要求:
选择元素需要具有批量选择(框选/划选),单项选择(按住Ctrl点选)的正选/反选功能,完成选择后需要在界面显示生成图表的预览图,具有生成默认图表与自定义图表的功能,并可输出为Excel格式的表格文件。
分析:
该工具大致可分为三个阶段:选择模型中元素阶段,界面中预览图表与参数设置阶段,放置图表阶段。其中第一个与最后一个阶段涉及到交互式工具的使用,而中间的阶段涉及到界面的交互。
Slide4.JPG
图2 表格生成工具流程图

  1. using Bentley.DgnPlatformNET;
  2. using Bentley.DgnPlatformNET.Elements;
  3. using Bentley.GeometryNET;
  4. using Bentley.MstnPlatformNET;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using ExampleofCase.UI;
  11. namespace ExampleofCase.DataAnalysisTool
  12. {
  13. class DataAnalysisCommand : DgnElementSetTool
  14. {
  15. public static List<Element> m_elems;//声明元素列表
  16. public DataAnalysisCommand(int toolId, int prompt) : base(toolId, prompt)//继承基类的构造函数
  17. {
  18. }
  19. public static void InstallNewInstance()//该命令的入口函数
  20. {
  21. DataAnalysisCommand primitiveTool = new DataAnalysisCommand(0, 0);//创建实例
  22. primitiveTool.InstallTool();//加载工具
  23. }
  24. public override StatusInt OnElementModify(Element element)
  25. {
  26. return StatusInt.Error;
  27. }
  28. protected override void OnRestartTool()
  29. {
  30. InstallNewInstance();
  31. }
  32. protected override void OnPostInstall()//工具激活后执行
  33. {
  34. string tips = "Please select elements to be analyzed:";//设置提示语
  35. NotificationManager.OutputPrompt(tips);//将提示语输出到提示框中
  36. m_elems = new List<Element>();//定义元素列表
  37. }
  38. protected override bool WantAdditionalLocate(DgnButtonEvent ev)//判断当前是否需要拾取元素
  39. {
  40. if (ev == null)//若没有选择到元素
  41. {
  42. return true;
  43. }
  44. if (ev.IsControlKey)//若检测到按动Ctrl行为
  45. {
  46. return true;
  47. }
  48. if (ElementAgenda.GetCount() == 0)//若选择集中没有元素
  49. {
  50. return true;
  51. }
  52. return false;
  53. }
  54. protected override bool OnResetButton(DgnButtonEvent ev)//重置键(默认右键)点击时触发
  55. {
  56. ExitTool();//退出交互式工具
  57. return true;
  58. }
  59. protected override UsesDragSelect AllowDragSelect()//判断是否要启用框选或者划选
  60. {
  61. return UsesDragSelect.Box;//使用框选选择元素
  62. }
  63. protected override bool NeedAcceptPoint()//判断是否需要用户再点击左键才开始处理元素
  64. {
  65. return false;
  66. }
  67. protected override bool OnModifyComplete(DgnButtonEvent ev)//修改完毕,对选择集中的元素进行处理
  68. {
  69. m_elems.Clear();//清空列表项
  70. for (uint i=0;i<ElementAgenda.GetCount();i++)//遍历选择集中的元素
  71. {
  72. m_elems.Add(ElementAgenda.GetEntry(i));//将选择集中的元素添加到列表中
  73. }
  74. if(m_elems.Count==0)//判断列表中元素个数
  75. {
  76. MessageCenter.Instance.ShowInfoMessage("No elements selected", "No elements selected", true);//输出未选择元素的提示
  77. return base.OnModifyComplete(ev);//返回并调用基类方法
  78. }
  79. MessageCenter.Instance.ShowInfoMessage("Element selection succeeded", "Element selection succeeded", false);//输出选中元素成功的提示
  80. DataFilterMenu menu = new DataFilterMenu();//声明界面
  81. menu.AttachToToolSettings(csAddins.MyAddin.Addin);//将界面添加到工具框中
  82. menu.Show();//显示界面
  83. return base.OnModifyComplete(ev);//返回并调用基类方法
  84. }
  85. }
  86. class ElementPlacementCommand : DgnElementSetTool
  87. {
  88. private const int WIDTH = 4000;//声明自定义图表的宽度
  89. private const int HEIGHT = 2000;//声明自定义图表的高度
  90. private List<Element> m_elems;//声明元素列表
  91. private Element m_textTableElem;//声明用于创建自定义图表的元素
  92. public ElementPlacementCommand(int toolId, int prompt) : base(toolId, prompt)//继承基类的构造函数
  93. {
  94. }
  95. public static void InstallNewInstance()//该命令的入口函数
  96. {
  97. ElementPlacementCommand primitiveTool = new ElementPlacementCommand(0, 0);//创建实例
  98. primitiveTool.InstallTool();//加载工具
  99. }
  100. public override StatusInt OnElementModify(Element element)
  101. {
  102. return StatusInt.Error;
  103. }
  104. protected override void OnRestartTool()
  105. {
  106. InstallNewInstance();
  107. }
  108. protected override void OnPostInstall()//工具激活后执行
  109. {
  110. string tips = "Please select elements to be analyzed:";//设置提示语
  111. NotificationManager.OutputPrompt(tips);//将提示语输出到提示框中
  112. m_elems = new List<Element>(DataFilterMenu.m_elems);//定义元素列表
  113. DrawDataTable();
  114. BeginDynamics();
  115. }
  116. protected override void OnDynamicFrame(DgnButtonEvent ev)
  117. {
  118. DynamicDrawElems(m_textTableElem, ev.Point);
  119. }
  120. protected override bool OnDataButton(DgnButtonEvent ev)
  121. {
  122. EndDynamics();
  123. PlaceDataTable(m_textTableElem, ev.Point);
  124. ExitTool();
  125. return true;
  126. }
  127. protected override bool OnResetButton(DgnButtonEvent ev)
  128. {
  129. ExitTool();
  130. return true;
  131. }
  132. private void DrawDataTable()
  133. {
  134. DgnFile dgnFile = Session.Instance.GetActiveDgnFile();//获得当前激活的文件
  135. DgnModel dgnModel = Session.Instance.GetActiveDgnModel();//获得当前激活的模型空间
  136. DgnTextStyle textStyle = DgnTextStyle.GetByName("Test1", dgnFile);//根据名称获得文字样式
  137. if (null == textStyle)//判断是否成功获取同名文字样式
  138. {
  139. textStyle = new DgnTextStyle("Test1", dgnFile);//在文件中定义文字样式
  140. DgnFont font = DgnFontManager.FindSystemFont("KaiTi", DgnFontFilterFlags.All);//获得名为"KaiTi"的字体
  141. textStyle.SetFontProperty(TextStyleProperty.Font, font);//设置字体
  142. textStyle.SetProperty(TextStyleProperty.Width, 1000D);//设置文字宽度
  143. textStyle.SetProperty(TextStyleProperty.Height, 1000D);//设置文字高度
  144. textStyle.Add(dgnFile);//将文字样式添加到文件中
  145. }
  146. ElementId textStyleId = textStyle.Id;//获得文字样式ID
  147. if (DataFilterMenu.m_tableInfo.Item1==true)//通过元组参数判断
  148. {
  149. uint tableRow = 0;//设置用于表示图表行的变量
  150. if(DataFilterMenu.m_tableInfo.Item2==0)//通过元组参数判断
  151. {
  152. tableRow = 6;//设置变量
  153. }
  154. else
  155. {
  156. tableRow = 2;//设置变量
  157. }
  158. TextTable textTable = TextTable.Create((uint)m_elems.Count+1, tableRow, textStyleId, 1000, dgnModel);//创建文字表
  159. {
  160. string nameDesc1 = "ID";//设置字符串
  161. string nameDesc2 = "Desc";
  162. if (DataFilterMenu.m_tableInfo.Item2 == 2)//通过元组参数判断
  163. {
  164. nameDesc1 = "Type";//设置字符串
  165. nameDesc2 = "IsInvisible";
  166. }
  167. else if(DataFilterMenu.m_tableInfo.Item2 == 3)//通过元组参数判断
  168. {
  169. nameDesc1 = "IsValid";//设置字符串
  170. nameDesc2 = "LevelId";
  171. }
  172. TableCellIndex index = new TableCellIndex(0, 0);//声明图表单元索引
  173. TextTableCell tableCell = textTable.GetCell(index);//通过索引值获得文字表单元
  174. tableCell.SetTextString(nameDesc1);//设置文字表单元名称
  175. index = new TableCellIndex(0, 1);//定义图表单元索引
  176. tableCell = textTable.GetCell(index);//通过索引值获得文字表单元
  177. tableCell.SetTextString(nameDesc2);//设置文字表单元名称
  178. if (DataFilterMenu.m_tableInfo.Item2 == 0)//通过元组参数判断
  179. {
  180. index = new TableCellIndex(0, 2);//声明图表单元索引
  181. tableCell = textTable.GetCell(index);//通过索引值获得文字表单元
  182. tableCell.SetTextString("Type");//设置文字表单元名称
  183. index = new TableCellIndex(0, 3);
  184. tableCell = textTable.GetCell(index);
  185. tableCell.SetTextString("IsInvisible");
  186. index = new TableCellIndex(0, 4);
  187. tableCell = textTable.GetCell(index);
  188. tableCell.SetTextString("IsValid");
  189. index = new TableCellIndex(0, 5);
  190. tableCell = textTable.GetCell(index);
  191. tableCell.SetTextString("LevelId");
  192. }
  193. }
  194. for (int i = 0; i < m_elems.Count; i++)//遍历元素列表
  195. {
  196. string nameDesc1 = m_elems[i].ElementId.ToString();//设置字符串
  197. string nameDesc2 = m_elems[i].Description;
  198. if (DataFilterMenu.m_tableInfo.Item2 == 2)//通过元组参数判断
  199. {
  200. nameDesc1 = m_elems[i].ElementType.ToString();//设置字符串
  201. nameDesc2 = m_elems[i].IsInvisible.ToString();
  202. }
  203. else if (DataFilterMenu.m_tableInfo.Item2 == 3)
  204. {
  205. nameDesc1 = m_elems[i].IsValid.ToString();
  206. nameDesc2 = m_elems[i].LevelId.ToString();
  207. }
  208. TableCellIndex index = new TableCellIndex((uint)i + 1, 0);//定义图表单元索引
  209. TextTableCell tableCell = textTable.GetCell(index);//通过索引值获得文字表单元
  210. tableCell.SetTextString(nameDesc1);//设置文字表单元名称
  211. index = new TableCellIndex((uint)i + 1, 1);
  212. tableCell = textTable.GetCell(index);
  213. tableCell.SetTextString(nameDesc2);
  214. if (DataFilterMenu.m_tableInfo.Item2 == 0)//通过元组参数判断
  215. {
  216. index = new TableCellIndex((uint)i + 1, 2);//定义图表单元索引
  217. tableCell = textTable.GetCell(index);//通过索引值获得文字表单元
  218. tableCell.SetTextString(m_elems[i].ElementType.ToString());//设置文字表单元名称
  219. index = new TableCellIndex((uint)i + 1, 3);
  220. tableCell = textTable.GetCell(index);
  221. tableCell.SetTextString(m_elems[i].IsInvisible.ToString());
  222. index = new TableCellIndex((uint)i + 1, 4);
  223. tableCell = textTable.GetCell(index);
  224. tableCell.SetTextString(m_elems[i].IsValid.ToString());
  225. index = new TableCellIndex((uint)i + 1, 5);
  226. tableCell = textTable.GetCell(index);
  227. tableCell.SetTextString(m_elems[i].LevelId.ToString());
  228. }
  229. }
  230. m_textTableElem = new TextTableElement(textTable);//声明文字表元素
  231. }
  232. else
  233. {
  234. IList<Element> subElems = new List<Element>();//声明元素列表
  235. #region DrawCustomDataTable
  236. int tableItems = 6;//设置Int变量
  237. if(DataFilterMenu.m_tableInfo.Item2 != 0)//通过元组参数判断
  238. {
  239. tableItems = 2;//修改Int变量值
  240. }
  241. for(int i=0;i<tableItems+1;i++)//遍历
  242. {
  243. DPoint3d startPo = new DPoint3d(i*WIDTH,0);//设置图表行线起点
  244. DPoint3d endPo = new DPoint3d(i * WIDTH, HEIGHT* m_elems.Count);//设置图表行线终点
  245. DSegment3d segment = new DSegment3d(startPo,endPo);//声明几何直线
  246. LineElement line = new LineElement(dgnModel, null, segment);//声明线元素
  247. subElems.Add(line);//将线元素添加到列表中
  248. }
  249. for (int i = 0; i < m_elems.Count+1; i++)//遍历
  250. {
  251. DPoint3d startPo = new DPoint3d(0, i*HEIGHT);//设置图表列线起点
  252. DPoint3d endPo = new DPoint3d(tableItems*WIDTH, i * HEIGHT);//设置图表列线终点
  253. DSegment3d segment = new DSegment3d(startPo, endPo);//声明几何直线
  254. LineElement line = new LineElement(dgnModel, null, segment);//声明线元素
  255. subElems.Add(line);//将线元素添加到列表中
  256. }
  257. #endregion
  258. #region InsertDataToDataTable
  259. for (int i = 0; i < tableItems; i++)//遍历
  260. {
  261. for (int j = 0; j < m_elems.Count; j++)//遍历
  262. {
  263. DPoint3d insertPo = new DPoint3d(i*WIDTH,(1+j)*HEIGHT);//设置文字插入点
  264. TextBlockProperties txtBlockProp = new TextBlockProperties(dgnModel);//定义文本属性
  265. txtBlockProp.IsViewIndependent = false;//设置文本非独立于视图
  266. ParagraphProperties paraProp = new ParagraphProperties(dgnModel);//定义段落属性
  267. RunProperties runProp = new RunProperties(textStyle, dgnModel);//定义运行属性
  268. TextBlock txtBlock = new TextBlock(txtBlockProp, paraProp, runProp, dgnModel);//定义文本块
  269. if (DataFilterMenu.m_tableInfo.Item2 == 0)//通过元组参数判断
  270. {
  271. switch(i)//分支判断
  272. {
  273. case 0:
  274. txtBlock.AppendText(m_elems[j].ElementId.ToString());//设置文本块文字内容
  275. break;
  276. case 1:
  277. txtBlock.AppendText(m_elems[j].Description);//设置文本块文字内容
  278. break;
  279. case 2:
  280. txtBlock.AppendText(m_elems[j].ElementType.ToString());//设置文本块文字内容
  281. break;
  282. case 3:
  283. txtBlock.AppendText(m_elems[j].IsInvisible.ToString());//设置文本块文字内容
  284. break;
  285. case 4:
  286. txtBlock.AppendText(m_elems[j].IsValid.ToString());//设置文本块文字内容
  287. break;
  288. case 5:
  289. txtBlock.AppendText(m_elems[j].LevelId.ToString());//设置文本块文字内容
  290. break;
  291. }
  292. }
  293. else if(DataFilterMenu.m_tableInfo.Item2 == 1)//通过元组参数判断
  294. {
  295. switch (i)//分支判断
  296. {
  297. case 0:
  298. txtBlock.AppendText(m_elems[j].ElementId.ToString());//设置文本块文字内容
  299. break;
  300. case 1:
  301. txtBlock.AppendText(m_elems[j].Description);//设置文本块文字内容
  302. break;
  303. }
  304. }
  305. else if (DataFilterMenu.m_tableInfo.Item2 == 2)//通过元组参数判断
  306. {
  307. switch (i)//分支判断
  308. {
  309. case 0:
  310. txtBlock.AppendText(m_elems[j].ElementType.ToString());//设置文本块文字内容
  311. break;
  312. case 1:
  313. txtBlock.AppendText(m_elems[j].IsInvisible.ToString());//设置文本块文字内容
  314. break;
  315. }
  316. }
  317. else if (DataFilterMenu.m_tableInfo.Item2 == 3)//通过元组参数判断
  318. {
  319. switch (i)//分支判断
  320. {
  321. case 0:
  322. txtBlock.AppendText(m_elems[j].IsValid.ToString());//设置文本块文字内容
  323. break;
  324. case 1:
  325. txtBlock.AppendText(m_elems[j].LevelId.ToString());//设置文本块文字内容
  326. break;
  327. }
  328. }
  329. TextElement text = (TextElement)TextElement.CreateElement(null, txtBlock);//定义文本元素
  330. TransformInfo transform = new TransformInfo(DTransform3d.FromTranslation(insertPo));//声明变换信息
  331. text.ApplyTransform(transform);//对元素应用变换信息
  332. subElems.Add(text);//将元素添加到列表中
  333. }
  334. }
  335. #endregion
  336. #region MergeIntoCell
  337. m_textTableElem = new CellHeaderElement(dgnModel, "CustomDataTable", DPoint3d.Zero, DMatrix3d.Identity,subElems);//声明单元元素
  338. #endregion
  339. }
  340. }
  341. private void DynamicDrawElems(Element element,DPoint3d locPo)
  342. {
  343. DTransform3d dTransform = DTransform3d.FromTranslation(locPo);//声明变换矩阵
  344. TransformInfo trans = new TransformInfo(dTransform);//声明变换信息
  345. element.ApplyTransform(trans);//对元素应用变换信息
  346. RedrawElems redrawElems = new RedrawElems();//使用元素用于动态绘制
  347. redrawElems.SetDynamicsViewsFromActiveViewSet(Session.GetActiveViewport());//设置视角
  348. redrawElems.DrawMode = DgnDrawMode.TempDraw;//设置绘制模式
  349. redrawElems.DrawPurpose = DrawPurpose.Dynamics;//设置绘制目标
  350. redrawElems.DoRedraw(element);//使用元素用于动态绘制
  351. dTransform.TryInvert(out DTransform3d dTransformInvert);//获得指定矩阵的逆矩阵
  352. trans = new TransformInfo(dTransformInvert);//声明变换信息
  353. element.ApplyTransform(trans);//对元素应用变换信息
  354. }
  355. private void PlaceDataTable(Element element, DPoint3d locPo)
  356. {
  357. TransformInfo trans = new TransformInfo(DTransform3d.FromTranslation(locPo));//声明变换信息
  358. element.ApplyTransform(trans);//对元素应用变换信息
  359. element.AddToModel();//将元素添加到模型中
  360. }
  361. }
  362. }
  1. using Bentley.DgnPlatformNET;
  2. using Bentley.DgnPlatformNET.Elements;
  3. using Bentley.GeometryNET;
  4. using Bentley.MstnPlatformNET.WinForms;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Data;
  8. using System.IO;
  9. using System.Text;
  10. using System.Windows.Forms;
  11. namespace ExampleofCase.UI
  12. {
  13. //在MicroStation二次开发的环境下使用WinForm时,需要将继承的Form修改为Bentley.MstnPlatformNET.WinForms.Adapter
  14. public partial class DataFilterMenu : Adapter// Form
  15. {
  16. public static Tuple<bool,int> m_tableInfo;//声明元组
  17. private DataTable m_dt;//声明数据列表
  18. public static List<Element> m_elems;//声明元素列表
  19. public DataFilterMenu()
  20. {
  21. InitializeComponent();
  22. }
  23. private void DataFilterMenu_Load(object sender, EventArgs e)//加载界面时触发
  24. {
  25. m_radioButton_usedefault.Checked = true;//设置单选按钮默认值
  26. m_button_importmodel.Enabled = false;//锁定按钮
  27. m_elems = new List<Element>(DataAnalysisTool.DataAnalysisCommand.m_elems);//定义元素列表
  28. }
  29. private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)//下拉框选择索引值修改后触发
  30. {
  31. RenewTableData();
  32. }
  33. private void button1_Click(object sender, EventArgs e)//按钮点击时触发
  34. {
  35. if (m_checkBox_exportExcel.Checked)//判断多选框是否处于选中状态
  36. {
  37. ExportDataGridToExcel();
  38. }
  39. m_tableInfo = new Tuple<bool, int>(m_radioButton_usedefault.Checked, m_comboBox_modelSelection.SelectedIndex);//定义元组
  40. this.Close();//关闭界面
  41. DataAnalysisTool.ElementPlacementCommand.InstallNewInstance();//启动交互式工具
  42. }
  43. private void RenewTableData()
  44. {
  45. m_dt = new DataTable();//定义数据表
  46. DataSet ds = new DataSet();//声明数据设置
  47. m_dt.TableName = " 元素信息 ";//设置图表名称
  48. ds.Tables.Add(m_dt);//在数据设置的图表中添加数据表
  49. if (m_comboBox_modelSelection.SelectedIndex==0|| m_comboBox_modelSelection.SelectedIndex == 1)//判断下拉框索引值
  50. {
  51. m_dt.Columns.Add(" ID ", typeof(string));//对数据表的列添加项
  52. m_dt.Columns.Add(" Desc ", typeof(string));
  53. }
  54. if(m_comboBox_modelSelection.SelectedIndex == 0 || m_comboBox_modelSelection.SelectedIndex == 2)
  55. {
  56. m_dt.Columns.Add(" Type ", typeof(string));
  57. m_dt.Columns.Add(" IsInvisible ", typeof(bool));
  58. }
  59. if(m_comboBox_modelSelection.SelectedIndex == 0 || m_comboBox_modelSelection.SelectedIndex == 3)
  60. {
  61. m_dt.Columns.Add(" IsValid ", typeof(bool));
  62. m_dt.Columns.Add(" LevelId ", typeof(string));
  63. }
  64. m_button_importmodel.Enabled = true;//激活按钮
  65. foreach (Element elem in m_elems)//遍历列表中的元素
  66. {
  67. DataRow drow = m_dt.NewRow();//新建数据行
  68. if (m_comboBox_modelSelection.SelectedIndex == 0 || m_comboBox_modelSelection.SelectedIndex == 1)//判断下拉框索引值
  69. {
  70. drow[" ID "] = elem.ElementId.ToString();//对数据行的列设置项
  71. drow[" Desc "] = elem.Description;
  72. }
  73. if (m_comboBox_modelSelection.SelectedIndex == 0 || m_comboBox_modelSelection.SelectedIndex == 2)
  74. {
  75. drow[" Type "] = elem.TypeName;
  76. drow[" IsInvisible "] = elem.IsInvisible;
  77. }
  78. if (m_comboBox_modelSelection.SelectedIndex == 0 || m_comboBox_modelSelection.SelectedIndex == 3)
  79. {
  80. drow[" IsValid "] = elem.IsValid;
  81. drow[" LevelId "] = elem.LevelId.ToString();
  82. }
  83. m_dt.Rows.Add(drow);//对数据表中添加数据行
  84. }
  85. m_dataGridView_elemProps.DataSource = m_dt;//设置数据源为定义的数据表
  86. }
  87. private void ExportDataGridToExcel()
  88. {
  89. SaveFileDialog exe = new SaveFileDialog();//声明文件保存对话框
  90. exe.Filter = "Execl files (*.xls)|*.xls";//确定筛选文件格式
  91. exe.FilterIndex = 0;//设置过滤器索引
  92. exe.RestoreDirectory = true;//设置保存目录
  93. exe.Title = "Export Excel File";//设置标题
  94. exe.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);//设置初始化文件存放位置
  95. exe.FileName = string.Format("{0}_{1}", DateTime.Now.ToString("yyyy-MM-dd HH时mm分ss秒"), "元素信息表");//设置文件名称
  96. DialogResult dr = exe.ShowDialog();//获得对话框结果
  97. if (dr != DialogResult.OK)//判断是否成功获取
  98. {
  99. return;//返回
  100. }
  101. #region 将DataTable中的数据转化为Excel格式的数据
  102. Stream ms = exe.OpenFile();
  103. StreamWriter sw = new StreamWriter(ms, Encoding.Default);
  104. string str = "";
  105. try
  106. {
  107. for (int i = 0; i < m_dt.Columns.Count; i++)
  108. {
  109. if (i > 0)
  110. {
  111. str += "\t";
  112. }
  113. str += m_dt.Columns[i];
  114. }
  115. sw.WriteLine(str);
  116. for (int j = 0; j < m_dt.Rows.Count; j++)
  117. {
  118. string temp = "";
  119. for (int k = 0; k < m_dt.Columns.Count; k++)
  120. {
  121. if (k > 0)
  122. {
  123. temp += "\t";
  124. }
  125. string cell = m_dt.Rows[j][k].ToString();
  126. cell = cell.Replace(" ", "").Replace("\r", "").Replace("\n", "").Replace("\r\n", "");
  127. temp += cell;
  128. }
  129. sw.WriteLine(temp);
  130. }
  131. sw.Close();
  132. ms.Close();
  133. }
  134. catch (Exception ex)
  135. {
  136. MessageBox.Show(ex.Message);
  137. return;
  138. }
  139. finally
  140. {
  141. sw.Close();
  142. ms.Close();
  143. }
  144. #endregion
  145. }
  146. }
  147. }
  1. namespace ExampleofCase.UI
  2. {
  3. partial class DataFilterMenu
  4. {
  5. /// <summary>
  6. /// Required designer variable.
  7. /// </summary>
  8. private System.ComponentModel.IContainer components = null;
  9. /// <summary>
  10. /// Clean up any resources being used.
  11. /// </summary>
  12. /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
  13. protected override void Dispose(bool disposing)
  14. {
  15. if (disposing && (components != null))
  16. {
  17. components.Dispose();
  18. }
  19. base.Dispose(disposing);
  20. }
  21. #region Windows Form Designer generated code
  22. /// <summary>
  23. /// Required method for Designer support - do not modify
  24. /// the contents of this method with the code editor.
  25. /// </summary>
  26. private void InitializeComponent()
  27. {
  28. System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle4 = new System.Windows.Forms.DataGridViewCellStyle();
  29. System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle5 = new System.Windows.Forms.DataGridViewCellStyle();
  30. System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle6 = new System.Windows.Forms.DataGridViewCellStyle();
  31. this.m_dataGridView_elemProps = new System.Windows.Forms.DataGridView();
  32. this.m_comboBox_modelSelection = new System.Windows.Forms.ComboBox();
  33. this.m_label_filter = new System.Windows.Forms.Label();
  34. this.m_button_importmodel = new System.Windows.Forms.Button();
  35. this.m_radioButton_usedefault = new System.Windows.Forms.RadioButton();
  36. this.m_radioButton_usecustom = new System.Windows.Forms.RadioButton();
  37. this.m_checkBox_exportExcel = new System.Windows.Forms.CheckBox();
  38. ((System.ComponentModel.ISupportInitialize)(this.m_dataGridView_elemProps)).BeginInit();
  39. this.SuspendLayout();
  40. //
  41. // m_dataGridView_elemProps
  42. //
  43. this.m_dataGridView_elemProps.AllowUserToAddRows = false;
  44. this.m_dataGridView_elemProps.AllowUserToDeleteRows = false;
  45. dataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
  46. dataGridViewCellStyle4.BackColor = System.Drawing.SystemColors.Control;
  47. dataGridViewCellStyle4.Font = new System.Drawing.Font("Microsoft YaHei UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  48. dataGridViewCellStyle4.ForeColor = System.Drawing.SystemColors.WindowText;
  49. dataGridViewCellStyle4.SelectionBackColor = System.Drawing.SystemColors.Highlight;
  50. dataGridViewCellStyle4.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
  51. dataGridViewCellStyle4.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
  52. this.m_dataGridView_elemProps.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle4;
  53. this.m_dataGridView_elemProps.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
  54. dataGridViewCellStyle5.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
  55. dataGridViewCellStyle5.BackColor = System.Drawing.SystemColors.Window;
  56. dataGridViewCellStyle5.Font = new System.Drawing.Font("Microsoft YaHei UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  57. dataGridViewCellStyle5.ForeColor = System.Drawing.SystemColors.ControlText;
  58. dataGridViewCellStyle5.SelectionBackColor = System.Drawing.SystemColors.Highlight;
  59. dataGridViewCellStyle5.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
  60. dataGridViewCellStyle5.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
  61. this.m_dataGridView_elemProps.DefaultCellStyle = dataGridViewCellStyle5;
  62. this.m_dataGridView_elemProps.Location = new System.Drawing.Point(12, 29);
  63. this.m_dataGridView_elemProps.Name = "m_dataGridView_elemProps";
  64. this.m_dataGridView_elemProps.ReadOnly = true;
  65. dataGridViewCellStyle6.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
  66. dataGridViewCellStyle6.BackColor = System.Drawing.SystemColors.Control;
  67. dataGridViewCellStyle6.Font = new System.Drawing.Font("Microsoft YaHei UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  68. dataGridViewCellStyle6.ForeColor = System.Drawing.SystemColors.WindowText;
  69. dataGridViewCellStyle6.SelectionBackColor = System.Drawing.SystemColors.Highlight;
  70. dataGridViewCellStyle6.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
  71. dataGridViewCellStyle6.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
  72. this.m_dataGridView_elemProps.RowHeadersDefaultCellStyle = dataGridViewCellStyle6;
  73. this.m_dataGridView_elemProps.Size = new System.Drawing.Size(479, 212);
  74. this.m_dataGridView_elemProps.TabIndex = 0;
  75. //
  76. // m_comboBox_modelSelection
  77. //
  78. this.m_comboBox_modelSelection.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
  79. this.m_comboBox_modelSelection.FormattingEnabled = true;
  80. this.m_comboBox_modelSelection.Items.AddRange(new object[] {
  81. "所有属性",
  82. "模式一",
  83. "模式二",
  84. "模式三"});
  85. this.m_comboBox_modelSelection.Location = new System.Drawing.Point(73, 4);
  86. this.m_comboBox_modelSelection.Name = "m_comboBox_modelSelection";
  87. this.m_comboBox_modelSelection.Size = new System.Drawing.Size(121, 21);
  88. this.m_comboBox_modelSelection.TabIndex = 1;
  89. this.m_comboBox_modelSelection.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
  90. //
  91. // m_label_filter
  92. //
  93. this.m_label_filter.AutoSize = true;
  94. this.m_label_filter.Font = new System.Drawing.Font("Microsoft YaHei UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  95. this.m_label_filter.Location = new System.Drawing.Point(11, 5);
  96. this.m_label_filter.Name = "m_label_filter";
  97. this.m_label_filter.Size = new System.Drawing.Size(56, 17);
  98. this.m_label_filter.TabIndex = 2;
  99. this.m_label_filter.Text = "过滤条件";
  100. //
  101. // m_button_importmodel
  102. //
  103. this.m_button_importmodel.Font = new System.Drawing.Font("Microsoft YaHei UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  104. this.m_button_importmodel.Location = new System.Drawing.Point(217, 257);
  105. this.m_button_importmodel.Name = "m_button_importmodel";
  106. this.m_button_importmodel.Size = new System.Drawing.Size(75, 23);
  107. this.m_button_importmodel.TabIndex = 3;
  108. this.m_button_importmodel.Text = "导入模型";
  109. this.m_button_importmodel.UseVisualStyleBackColor = true;
  110. this.m_button_importmodel.Click += new System.EventHandler(this.button1_Click);
  111. //
  112. // m_radioButton_usedefault
  113. //
  114. this.m_radioButton_usedefault.AutoSize = true;
  115. this.m_radioButton_usedefault.Font = new System.Drawing.Font("Microsoft YaHei UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  116. this.m_radioButton_usedefault.Location = new System.Drawing.Point(14, 247);
  117. this.m_radioButton_usedefault.Name = "m_radioButton_usedefault";
  118. this.m_radioButton_usedefault.Size = new System.Drawing.Size(74, 21);
  119. this.m_radioButton_usedefault.TabIndex = 4;
  120. this.m_radioButton_usedefault.TabStop = true;
  121. this.m_radioButton_usedefault.Text = "内置图表";
  122. this.m_radioButton_usedefault.UseVisualStyleBackColor = true;
  123. //
  124. // m_radioButton_usecustom
  125. //
  126. this.m_radioButton_usecustom.AutoSize = true;
  127. this.m_radioButton_usecustom.Font = new System.Drawing.Font("Microsoft YaHei UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  128. this.m_radioButton_usecustom.Location = new System.Drawing.Point(14, 270);
  129. this.m_radioButton_usecustom.Name = "m_radioButton_usecustom";
  130. this.m_radioButton_usecustom.Size = new System.Drawing.Size(86, 21);
  131. this.m_radioButton_usecustom.TabIndex = 5;
  132. this.m_radioButton_usecustom.TabStop = true;
  133. this.m_radioButton_usecustom.Text = "自定义图表";
  134. this.m_radioButton_usecustom.UseVisualStyleBackColor = true;
  135. //
  136. // m_checkBox_exportExcel
  137. //
  138. this.m_checkBox_exportExcel.AutoSize = true;
  139. this.m_checkBox_exportExcel.Font = new System.Drawing.Font("Microsoft YaHei UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  140. this.m_checkBox_exportExcel.Location = new System.Drawing.Point(411, 6);
  141. this.m_checkBox_exportExcel.Name = "m_checkBox_exportExcel";
  142. this.m_checkBox_exportExcel.Size = new System.Drawing.Size(80, 21);
  143. this.m_checkBox_exportExcel.TabIndex = 6;
  144. this.m_checkBox_exportExcel.Text = "导出Excel";
  145. this.m_checkBox_exportExcel.UseVisualStyleBackColor = true;
  146. //
  147. // DataFilterMenu
  148. //
  149. this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
  150. this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
  151. this.ClientSize = new System.Drawing.Size(505, 292);
  152. this.Controls.Add(this.m_checkBox_exportExcel);
  153. this.Controls.Add(this.m_radioButton_usecustom);
  154. this.Controls.Add(this.m_radioButton_usedefault);
  155. this.Controls.Add(this.m_button_importmodel);
  156. this.Controls.Add(this.m_label_filter);
  157. this.Controls.Add(this.m_comboBox_modelSelection);
  158. this.Controls.Add(this.m_dataGridView_elemProps);
  159. this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
  160. this.MaximizeBox = false;
  161. this.Name = "DataFilterMenu";
  162. this.ShowIcon = false;
  163. this.Text = "DataFilterMenu";
  164. this.TopMost = true;
  165. this.Load += new System.EventHandler(this.DataFilterMenu_Load);
  166. ((System.ComponentModel.ISupportInitialize)(this.m_dataGridView_elemProps)).EndInit();
  167. this.ResumeLayout(false);
  168. this.PerformLayout();
  169. }
  170. #endregion
  171. private System.Windows.Forms.DataGridView m_dataGridView_elemProps;
  172. private System.Windows.Forms.ComboBox m_comboBox_modelSelection;
  173. private System.Windows.Forms.Label m_label_filter;
  174. private System.Windows.Forms.Button m_button_importmodel;
  175. private System.Windows.Forms.RadioButton m_radioButton_usedefault;
  176. private System.Windows.Forms.RadioButton m_radioButton_usecustom;
  177. private System.Windows.Forms.CheckBox m_checkBox_exportExcel;
  178. }
  179. }

1.gif
图3 表格生成工具

图纸自动生成工具

  1. 在目前的设计模式中,作为表达工程信息的载体,如何生成一系列符合标准的图纸是衡量价值的重要标准,同时,生成图纸的效率与准确性也体现了生产力与质量。对于一些较为标准的构件,我们可以根据其特点抽象出其构建规则,以适用于该大类的所有构件,使用二次开发的方式自动根据模型信息生成图纸,与传统的图纸绘制相比,从模型到图纸的过程使用编程的方式自动生成,从而大幅度的提高制图效率。

需求说明:
使用工具对生成的构件进行图纸的输出。
要求:
通过绘制确定构件的最终形态,并在生成的图纸上对构件执行二维标注。
分析:
该工具大致可分为两个阶段:绘制构件阶段与生成图纸阶段,前者需要使用交互式工具,绘制出用于出图的构件,后者会依次创建NamedBoundary,SavedView与DrawingModel,并将SavedView参考到模型中,最后执行图纸中构件的标注。

Slide6.JPG
图4 图纸自动生成工具流程图

  1. using Bentley.DgnPlatformNET;
  2. using Bentley.DgnPlatformNET.Elements;
  3. using Bentley.GeometryNET;
  4. using Bentley.MstnPlatformNET;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. namespace ExampleofCase.CreateBeamDrawing
  9. {
  10. class CreateBeamDrawingCommand : DgnElementSetTool
  11. {
  12. #region enum
  13. private enum ViewType//设置枚举类型
  14. {
  15. MainView,//枚举项
  16. LeftView,
  17. VerticalView
  18. }
  19. #endregion
  20. private List<DPoint3d> m_pos;//声明坐标列表
  21. private DgnFile m_dgnFile;//声明文件
  22. private DgnModel m_dgnModel;//声明模型空间
  23. private double m_uorPerMilliMeter;//声明单位分辨率与毫米的比值
  24. public CreateBeamDrawingCommand(int toolId, int prompt) : base(toolId, prompt)//继承基类的构造函数
  25. {
  26. }
  27. public static void InstallNewInstance()//该命令的入口函数
  28. {
  29. CreateBeamDrawingCommand primitiveTool = new CreateBeamDrawingCommand(0, 0);//创建实例
  30. primitiveTool.InstallTool();//加载工具
  31. }
  32. /*
  33. * 如果我们对通过参数传递进来的元素进行修改,并且返回SUCCESS的话,在_DoOperationForModify
  34. * 中会用修改后的元素替换掉原来的元素,当然前提是_IsModifyOriginal返回true。否则的话会直接
  35. * 把修改后的元素重新添加到Dgn文件中。
  36. */
  37. public override StatusInt OnElementModify(Element element)
  38. {
  39. return StatusInt.Error;
  40. }
  41. protected override void OnRestartTool()//重启工具时触发
  42. {
  43. }
  44. protected override void OnPostInstall()//工具激活后执行
  45. {
  46. m_dgnFile = Session.Instance.GetActiveDgnFile();//获得当前激活的文件
  47. m_dgnModel = Session.Instance.GetActiveDgnModel();//获得当前激活的模型
  48. m_uorPerMilliMeter = Session.Instance.GetActiveDgnModel().GetModelInfo().UorPerMeter / 1000;//分辨率单位转换为毫米
  49. m_pos = new List<DPoint3d>();//初始化列表
  50. }
  51. protected override bool OnDataButton(DgnButtonEvent ev)//点击确认键(默认为左键)后触发
  52. {
  53. if (m_pos.Count() == 0)//判断列表中的坐标点个数
  54. {
  55. m_pos.Add(ev.Point);//将坐标值添加到列表中
  56. BeginDynamics();//启动动态绘制
  57. return true;//返回
  58. }
  59. else
  60. {
  61. EndDynamics();//关闭动态绘制
  62. m_pos.Add(ev.Point);//将坐标值添加到列表中
  63. Element solid= CreateBeamElem();//创建构建梁的元素
  64. CreateBeamDrawing(solid);
  65. m_pos.Clear();//清空列表
  66. return true;//返回
  67. }
  68. }
  69. protected override bool OnResetButton(DgnButtonEvent ev)//点击重置键(默认为右键)触发
  70. {
  71. if (m_pos.Count() == 0)//判断列表中坐标点个数是否为零
  72. {
  73. ExitTool();//退出工具
  74. }
  75. else
  76. {
  77. EndDynamics();//关闭动态绘制
  78. m_pos.Clear();//清空列表
  79. }
  80. return true;
  81. }
  82. protected override void OnDynamicFrame(DgnButtonEvent ev)//动态绘制时触发
  83. {
  84. ShapeElement m_beamProfile = CreateBeamProfile(m_pos[0]);//创建形元素用于确定梁截面
  85. Element element = CreateSolidElement(m_pos[0], ev.Point, m_beamProfile);//创建梁实体元素
  86. if (null == element)//若未成功生成梁实体元素
  87. return;//返回
  88. DynamicDrawElems(element);//动态绘制元素
  89. }
  90. private ShapeElement CreateBeamProfile(DPoint3d startPo)//创建用于表达梁截面的形元素
  91. {
  92. DPoint3d[] pos =
  93. {
  94. new DPoint3d(startPo.X-0.5*400*m_uorPerMilliMeter,startPo.Y,startPo.Z),
  95. new DPoint3d(startPo.X-0.5*400*m_uorPerMilliMeter,startPo.Y,startPo.Z-1*600*m_uorPerMilliMeter),
  96. new DPoint3d(startPo.X+0.5*400*m_uorPerMilliMeter,startPo.Y,startPo.Z-1*600*m_uorPerMilliMeter),
  97. new DPoint3d(startPo.X+0.5*400*m_uorPerMilliMeter,startPo.Y,startPo.Z)
  98. };//确定梁截面端点坐标集
  99. ShapeElement beamProfile = new ShapeElement(m_dgnModel, null, pos);//创建表达梁截面的形元素
  100. return beamProfile;//返回梁截面的形元素
  101. }
  102. private void DynamicDrawElems(Element element)
  103. {
  104. RedrawElems redrawElems = new RedrawElems();//使用元素用于动态绘制
  105. redrawElems.SetDynamicsViewsFromActiveViewSet(Session.GetActiveViewport());//设置视角
  106. redrawElems.DrawMode = DgnDrawMode.TempDraw;//设置绘制模式
  107. redrawElems.DrawPurpose = DrawPurpose.Dynamics;//设置绘制目标
  108. redrawElems.DoRedraw(element);//使用元素用于动态绘制
  109. }
  110. private SurfaceOrSolidElement CreateSolidElement(DPoint3d startPo, DPoint3d endPo, ShapeElement beamProfile)
  111. {
  112. DVector3d vector = new DVector3d(startPo, endPo);//声明梁方向向量
  113. if (vector == DVector3d.Zero)//判断是否成功获取
  114. {
  115. return null;//返回空
  116. }
  117. TransformInfo trans = new TransformInfo(DTransform3d.FromRotationAroundLine(startPo, DVector3d.UnitZ, vector.Rotate90CCWXY().AngleXY));//声明变换信息
  118. beamProfile.ApplyTransform(trans);//对形元素施加变换
  119. SurfaceOrSolidElement solid = SolidElement.CreateProjectionElement(m_dgnModel, null, beamProfile, startPo, vector, DTransform3d.Identity, true);//创建拉伸实体
  120. return solid;//返回拉伸实体
  121. }
  122. private Element CreateBeamElem()
  123. {
  124. ShapeElement beamProfile = CreateBeamProfile(m_pos[0]);//创建表达梁截面的形元素
  125. SurfaceOrSolidElement solid = CreateSolidElement(m_pos[0], m_pos[1], beamProfile);//创建拉伸实体元素
  126. solid.AddToModel();//将拉伸实体元素写入模型
  127. return solid;//返回拉伸实体元素
  128. }
  129. private void CreateDimensionElem(List<DPoint3d> pos,DgnModel dgnModel, ViewType viewType)
  130. {
  131. List<DPoint3d> reverserPos = new List<DPoint3d>();//声明用于储存坐标的列表
  132. switch (viewType)//分支判断
  133. {
  134. case ViewType.VerticalView://若viewType为ViewType.VerticalView
  135. reverserPos.Add(pos[0]);//对列表添加坐标
  136. reverserPos.Add(pos[1]);
  137. break;
  138. case ViewType.MainView:
  139. reverserPos.Add(new DPoint3d(pos[0].Y, -pos[0].Z));
  140. reverserPos.Add(new DPoint3d(pos[1].Y, -pos[1].Z));
  141. break;
  142. case ViewType.LeftView:
  143. reverserPos.Add(new DPoint3d(pos[0].X, pos[0].Z));
  144. reverserPos.Add(new DPoint3d(pos[1].X, pos[1].Z));
  145. break;
  146. }
  147. //获取当前dgn文件中名字为"DimStyle"的标注样式,尺寸标注元素的外貌由上百个属性控制,而标注样式是一组预先设置好的属性
  148. //获取了预先订制好的标注样式之后,还可以调用DimensionStyle下的各种SetXXX成员函数修改设置的属性
  149. DimensionStyle dimStyle = new DimensionStyle("DimStyle", m_dgnFile);//定义标注样式
  150. dimStyle.SetBooleanProp(true, DimStyleProp.Placement_UseStyleAnnotationScale_BOOLINT);//设置标注样式
  151. dimStyle.SetDoubleProp(1, DimStyleProp.Placement_AnnotationScale_DOUBLE);
  152. dimStyle.SetBooleanProp(true, DimStyleProp.Text_OverrideHeight_BOOLINT);
  153. dimStyle.SetDistanceProp(0.2 * 10000, DimStyleProp.Text_Height_DISTANCE, dgnModel);
  154. dimStyle.SetBooleanProp(true, DimStyleProp.Text_OverrideWidth_BOOLINT);
  155. dimStyle.SetDistanceProp(0.2 * 10000, DimStyleProp.Text_Width_DISTANCE, dgnModel);
  156. dimStyle.SetBooleanProp(true, DimStyleProp.General_UseMinLeader_BOOLINT);
  157. dimStyle.SetDoubleProp(0.01, DimStyleProp.Terminator_MinLeader_DOUBLE);
  158. dimStyle.SetBooleanProp(true, DimStyleProp.Value_AngleMeasure_BOOLINT);
  159. dimStyle.SetAccuracyProp((byte)AnglePrecision.Use1Place, DimStyleProp.Value_AnglePrecision_INTEGER);
  160. int alignInt = (int)DimStyleProp_General_Alignment.True;
  161. StatusInt status = dimStyle.SetIntegerProp(alignInt, DimStyleProp.General_Alignment_INTEGER);
  162. dimStyle.GetIntegerProp(out int valueOut, DimStyleProp.General_Alignment_INTEGER);
  163. DgnTextStyle textStyle = new DgnTextStyle("TestStyle", m_dgnFile);//设置文字样式
  164. LevelId lvlId = Settings.GetLevelIdFromName("Default");//设置图层
  165. CreateDimensionCallbacks callbacks1 = new CreateDimensionCallbacks(dimStyle, textStyle, new Symbology(), lvlId, null);//尺寸标注元素的构造函数会调用DimensionCreateData的各个成员函数去获取定义尺寸标注元素需要的各种参数
  166. CreateDimensionElem(dgnModel,reverserPos, callbacks1,dimStyle,DMatrix3d.Identity);//调用封装的方法创建标注元素
  167. Angle angle = new Angle();//声明角度
  168. angle.Degrees = 90;//设置角度为90度
  169. DMatrix3d matrix = DMatrix3d.XYRotation(angle);//声明旋转90度的变换矩阵
  170. CreateDimensionCallbacks callbacks2 = new CreateDimensionCallbacks(dimStyle, textStyle, new Symbology(), lvlId, null);//尺寸标注元素的构造函数会调用DimensionCreateData的各个成员函数去获取定义尺寸标注元素需要的各种参数
  171. CreateDimensionElem(dgnModel, reverserPos, callbacks2, dimStyle, matrix);//调用封装的方法创建标注元素
  172. }
  173. private void CreateDimensionElem(DgnModel dgnModel, List<DPoint3d> reverserPos, CreateDimensionCallbacks callbacks, DimensionStyle dimStyle, DMatrix3d matrix)
  174. {
  175. DimensionElement dimEle = new DimensionElement(dgnModel, callbacks, DimensionType.SizeStroke);//定义标注元素
  176. if (dimEle.IsValid)//判断标注元素是否有效
  177. {
  178. for (int i = 0; i < reverserPos.Count(); i++)//遍历列表
  179. {
  180. dimEle.InsertPoint(reverserPos[i] - reverserPos[0] - 0.5 * (reverserPos[1] - reverserPos[0]), null, dimStyle, -1);//对标注元素设置插入点
  181. }
  182. dimEle.SetHeight(2 * 10000);//设置尺寸标注元素的高度
  183. dimEle.SetRotationMatrix(DMatrix3d.Identity);//设置变换信息
  184. }
  185. dimEle.SetRotationMatrix(matrix);//对标注元素应用变换矩阵
  186. dimEle.AddToModel();//将标注元素添加到模型
  187. }
  188. private void CreateBeamDrawing(Element solid)
  189. {
  190. for (int i=0;i<3;i++)//遍历
  191. {
  192. string sheetModelName = "drawingModel";//设置字符串
  193. string namedViewName = "testNamedView";
  194. string groupName = "testGroupName";
  195. string boundaryName = "testBoundName";
  196. sheetModelName = sheetModelName + i;//设置sheet模型名称
  197. namedViewName = namedViewName + i;//设置NamedView名称
  198. groupName += i;//设置NamedGroup名称
  199. boundaryName += i;//设置NamedBoundary名称
  200. ViewType viewType = ViewType.VerticalView;//设置枚举默认值
  201. StandardView stView = StandardView.Top;//设置视图视角
  202. switch (i)//分支判断变量
  203. {
  204. case 1://若i等于1
  205. viewType = ViewType.MainView;//设置枚举值
  206. stView = StandardView.Left;//设置视角值
  207. break;//跳出分支
  208. case 2:
  209. viewType = ViewType.LeftView;
  210. stView = StandardView.Front;
  211. break;
  212. }
  213. NamedBoundary boundary = CreateNamedBoundary(solid, groupName, boundaryName);//使用封装的方法创建NamedBoundary
  214. ViewInformation viewInfo = ZoomElementView(solid, out ShapeElement shape, viewType);//使用封装的方法获得视图信息
  215. NamedView view = CreateNamedView(shape, viewInfo, namedViewName);//使用封装的方法创建NamedView
  216. DgnModel drawingModel = CreateDrawingModel(sheetModelName, view, stView);//使用封装的方法创建DrawingModel
  217. CreateDimensionElem(m_pos, drawingModel, viewType);//使用封装的方法创建标注元素
  218. }
  219. }
  220. private DgnModel CreateDrawingModel(string name, NamedView namedView, StandardView viewMode)
  221. {
  222. DgnModel drawingModel = m_dgnFile.CreateNewModel(out DgnModelStatus error, name, DgnModelType.Drawing, false, null);//在指定文件中创建新模型
  223. DgnAttachment refToCreate = drawingModel.CreateDgnAttachment(m_dgnFile.GetDocument().GetMoniker(), name);//创建模型参照
  224. refToCreate.ApplyNamedView(namedView.Name, 1, 1, new ApplyViewClipOptions(), true, viewMode);//对模型参照添加NamedView
  225. refToCreate.WriteToModel(true);//将模型参照写入模型
  226. refToCreate.NestDepth = 99;//设置深度
  227. refToCreate.SetLocateLock(true);//锁定定位
  228. refToCreate.SetSnapLock(true);//锁定捕捉
  229. return drawingModel;//返回模型
  230. }
  231. private NamedView CreateNamedView(ShapeElement shape, ViewInformation viewInfo,string namedViewName)
  232. {
  233. NamedView view = new NamedView(m_dgnFile, namedViewName);//声明NamedView
  234. view.SetClipElement(shape);//设置剪切元素
  235. view.SetViewInfo(viewInfo);//设置视图信息
  236. view.WriteToFile();//将视图写入文件
  237. return view;//返回视图
  238. }
  239. private ViewInformation ZoomElementView(Element elem, out ShapeElement shape, ViewType viewType)
  240. {
  241. DisplayableElement displayele = elem as DisplayableElement;//转换为显示元素
  242. displayele.CalcElementRange(out DRange3d rangeElem);//计算元素范围框
  243. DPoint3d[] pos=null;//声明坐标数组
  244. switch (viewType)//分支判断
  245. {
  246. case ViewType.VerticalView://若viewType为ViewType.VerticalView
  247. {
  248. pos = new DPoint3d[]//定义坐标数组
  249. {
  250. new DPoint3d(rangeElem.Low.X, rangeElem.Low.Y, 0.5 * (rangeElem.Low.Z + rangeElem.High.Z)),
  251. new DPoint3d(rangeElem.High.X, rangeElem.Low.Y, 0.5 * (rangeElem.Low.Z + rangeElem.High.Z)),
  252. new DPoint3d(rangeElem.High.X, rangeElem.High.Y, 0.5 * (rangeElem.Low.Z + rangeElem.High.Z)),
  253. new DPoint3d(rangeElem.Low.X, rangeElem.High.Y, 0.5 * (rangeElem.Low.Z + rangeElem.High.Z)),
  254. };
  255. break;//跳出分支判断
  256. }
  257. case ViewType.MainView:
  258. {
  259. pos = new DPoint3d[]
  260. {
  261. new DPoint3d(rangeElem.Low.X, 0.5*(rangeElem.Low.Y+ rangeElem.High.Y), rangeElem.Low.Z),
  262. new DPoint3d(rangeElem.High.X,0.5*(rangeElem.Low.Y+ rangeElem.High.Y), rangeElem.Low.Z),
  263. new DPoint3d(rangeElem.High.X,0.5*(rangeElem.Low.Y+ rangeElem.High.Y), rangeElem.High.Z),
  264. new DPoint3d(rangeElem.Low.X, 0.5*(rangeElem.Low.Y+ rangeElem.High.Y), rangeElem.High.Z),
  265. };
  266. break;
  267. }
  268. case ViewType.LeftView:
  269. {
  270. pos = new DPoint3d[]
  271. {
  272. new DPoint3d(0.5*(rangeElem.Low.X+ rangeElem.High.X), rangeElem.Low.Y, rangeElem.Low.Z),
  273. new DPoint3d(0.5*(rangeElem.Low.X+ rangeElem.High.X),rangeElem.High.Y, rangeElem.Low.Z),
  274. new DPoint3d(0.5*(rangeElem.Low.X+ rangeElem.High.X),rangeElem.High.Y, rangeElem.High.Z),
  275. new DPoint3d(0.5*(rangeElem.Low.X+ rangeElem.High.X), rangeElem.Low.Y, rangeElem.High.Z),
  276. };
  277. break;
  278. }
  279. }
  280. shape = new ShapeElement(m_dgnModel,null, pos);//使用坐标数组定义形元素
  281. double rL = rangeElem.High.X - rangeElem.Low.X ,
  282. rW = rangeElem.High.Y - rangeElem.Low.Y,
  283. rH = rangeElem.High.Z - rangeElem.Low.Z;//计算视图需要所需的范围(x,y,z)
  284. ViewGroupCollection viewcoll = m_dgnFile.GetViewGroups();//获得当前视图组集合
  285. ViewGroup viewgroup = viewcoll.GetActive();//获得当前激活的视图组
  286. viewgroup.FindFirstOpenView(out int viewnumber);//获得第一个打开的视图
  287. ViewInformation viewinfo = viewgroup.GetViewInformation(viewnumber);//获得指定视图编号的视图信息
  288. //设置视图参数
  289. DPoint3d delta = DPoint3d.FromXYZ(rL, rW, rH);//设置视图范围参数
  290. DMatrix3d rotmax = DMatrix3d.Identity;//设置变换参数
  291. //设置视图范围
  292. viewinfo.SetGeometry(rangeElem.Low, delta, rotmax);//对视图信息设置范围框
  293. //viewgroup.SetViewInformation(viewinfo, viewnumber);
  294. //viewgroup.SaveChanges();
  295. //viewgroup.SynchViewDisplay(viewnumber, false, true, false);
  296. ////更新视图
  297. //Session.Instance.Keyin("update view extended");
  298. return viewinfo;
  299. }
  300. private NamedBoundary CreateNamedBoundary(Element elem,string boundaryGroupName,string boundaryName)
  301. {
  302. NamedBoundaryGroup boundaryGroup = NamedBoundaryGroup.CreateNamedBoundaryGroup(Session.Instance.GetActiveDgnModel(), boundaryGroupName, "");//创建NamedBoundaryGroup
  303. NamedBoundary boundary = new NamedBoundary();//声明NamedGroup
  304. boundary.ModelRef = m_dgnModel;//设置NamedGroup参照模型
  305. boundary.Name = boundaryName;//设置NamedGroup名称
  306. boundary.DrawingScale = 1;//设置NamedGroup绘制比例
  307. boundary.GraphicalElement = elem;//设置NamedGroup图像元素
  308. boundary.Save();//保存NamedGroup设置
  309. boundaryGroup.InsertBoundary(boundary);//在NamedBoundaryGroup中导入NamedGroup
  310. boundaryGroup.WriteToFile();//将NamedBoundaryGroup信息写入
  311. return boundary;//返回NamedBoundary
  312. }
  313. }
  314. class CreateDimensionCallbacks : DimensionCreateData
  315. {
  316. private DimensionStyle m_dimStyle;
  317. private DgnTextStyle m_textStyle;
  318. private Symbology m_symbology;
  319. private LevelId m_levelId;
  320. private DirectionFormatter m_directionFormatter;
  321. public CreateDimensionCallbacks(DimensionStyle dimStyle, DgnTextStyle textStyle, Symbology symb, LevelId levelId, DirectionFormatter formatter)
  322. {
  323. m_dimStyle = dimStyle;
  324. m_textStyle = textStyle;
  325. m_symbology = symb;
  326. m_levelId = levelId;
  327. m_directionFormatter = formatter;
  328. }
  329. public override DimensionStyle GetDimensionStyle()
  330. {
  331. return m_dimStyle;
  332. }
  333. public override DgnTextStyle GetTextStyle()
  334. {
  335. return m_textStyle;
  336. }
  337. public override Symbology GetSymbology()
  338. {
  339. return m_symbology;
  340. }
  341. public override LevelId GetLevelId()
  342. {
  343. return m_levelId;
  344. }
  345. public override int GetViewNumber()
  346. {
  347. return 0;
  348. }
  349. //此函数返回的旋转矩阵与GetViewRotation返回的旋转矩阵共同定义了尺寸标注元素的方向
  350. public override DMatrix3d GetDimensionRotation()
  351. {
  352. return DMatrix3d.Identity;
  353. }
  354. public override DMatrix3d GetViewRotation()
  355. {
  356. return DMatrix3d.Identity;
  357. }
  358. //用于从数字方向值构造字符串。
  359. public override DirectionFormatter GetDirectionFormatter()
  360. {
  361. return m_directionFormatter;
  362. }
  363. }
  364. }

2.gif
图5 图纸自动生成工具

工程属性与几何构件联动案例

  1. BIM模型作为工程信息的载体,其中的几何元素必将与实际的工程属性相关联。对于参数化模型来说,假如构件上的参数过多,那么在安置后若多个参数化构件同时存在时,就会存在卡顿的现象。<br /> 本案例中针对的是在放置构件并调整工程属性后,所设定的模型参数会实时进行刷新并在构件模型上得以体现,同时在放置后在**没有对工程属性有修改需求**的场景下适用。这样做的好处是在生成构件模型时构件本身并没有被施加参数,在多个构件同时存在的模型中相较于参数化模型,大大提高模型的承载能力与响应速度。<br /> 该案例主要是用到Addin中的事件,它可以监控用户的行为,在用户执行执行行为时就会触发事件,跳转到对应的业务函数中,因此掌握方法的使用对于MicroStation二次开发来说也非常重要。本案例仅是浅尝辄止的为大家介绍了关于工程属性变化的事件,在后续的系列课程中会对其进行详细的介绍。<br />![Slide8.JPG](https://cdn.nlark.com/yuque/0/2022/jpeg/21640708/1647502828187-5f0a6603-4b07-4cfd-91ac-839c5da3ae18.jpeg#clientId=u83c9c1d1-6320-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=576&id=ufa6ccacf&margin=%5Bobject%20Object%5D&name=Slide8.JPG&originHeight=720&originWidth=1280&originalType=binary&ratio=1&rotation=0&showTitle=false&size=62486&status=done&style=none&taskId=u3157445a-8ff9-44e3-9fbd-64bd2915772&title=&width=1024)<br />**图6 工程属性与元素几何联动流程图**
  1. using Bentley.DgnPlatformNET;
  2. using Bentley.DgnPlatformNET.DgnEC;
  3. using Bentley.DgnPlatformNET.Elements;
  4. using Bentley.ECObjects.Instance;
  5. using Bentley.GeometryNET;
  6. using Bentley.MstnPlatformNET;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. using System.Windows;
  13. namespace ExampleofCase.ElemPropAutoChangedTool
  14. {
  15. class ElemPropAutoChangedCommand
  16. {
  17. private static DgnFile m_dgnFile;//声明文件
  18. private static DgnModel m_dgnModel;//声明模型空间
  19. private const string ITEMTYPELIB = "testLib";//设置ItemTypeLibrary的名称
  20. private const string ITEMTYPE = "testItemType";//设置ItemType的名称
  21. private const string ITEMPROP = "Length";//设置ItemType属性名称
  22. internal static void LanchEvent()
  23. {
  24. m_dgnFile = Session.Instance.GetActiveDgnFile();//定义文件
  25. m_dgnModel = Session.Instance.GetActiveDgnModel();//定义模型空间
  26. if(!CreateECInfo())
  27. {
  28. return;//返回
  29. }
  30. Element element= CreateComplexSolid(10);
  31. AttachItemTypeToElem(element);
  32. csAddins.MyAddin.Addin.XAttributeChangedEvent += Addin_XAttributeChangedEvent;//添加全局事件,当XAttribute变化时触发
  33. }
  34. private static void AttachItemTypeToElem(Element elem)
  35. {
  36. ItemTypeLibrary itemTypeLibrary = ItemTypeLibrary.FindByName(ITEMTYPELIB, m_dgnFile);//根据声明名称获取对应的ItemTypeLibrary
  37. if (null == itemTypeLibrary)//判断文件中是否存在同名ItemTypeLibrary
  38. {
  39. MessageBox.Show("Can't find ItemType Library");//若文件中不存在同名ItemTypeLibrary,则对话框提示未找到ItemTypeLibrary的提示框
  40. return;//返回
  41. }
  42. ItemType itemType = itemTypeLibrary.GetItemTypeByName(ITEMTYPE);//根据声明名称获取对应的ItemType
  43. CustomItemHost host = new CustomItemHost(elem, true);//声明元素的CustomItemHost
  44. IDgnECInstance item = host.ApplyCustomItem(itemType, true);//对CustomItemHost添加ItemType得到EC实例
  45. item.SetValue(ITEMPROP, 10);//设置属性值
  46. EditParameterDefinitions defs = EditParameterDefinitions.GetForModel(m_dgnModel);//获得模型中的参数定义
  47. DgnECInstanceEnabler enabler = DgnECManager.Manager.ObtainInstanceEnabler(m_dgnFile, itemType.ECClass);//获得文件中使用指定EC类的EC实例
  48. if (null != enabler && enabler.SupportsCreateInstanceOnElement)//判断是否是否支持对元素挂接EC实例
  49. defs.SetDomainParameters(enabler.SharedWipInstance);//对参数定义设置域参数
  50. item.ScheduleChanges(elem);//对圆锥(台)元素更新ItemType信息
  51. elem.AddToModel();//将圆锥(台)写入模型
  52. }
  53. private static bool CreateECInfo()
  54. {
  55. ItemTypeLibrary itemTypeLibrary = ItemTypeLibrary.FindByName(ITEMTYPELIB, m_dgnFile);//根据声明名称获取对应的ItemTypeLibrary
  56. if (null == itemTypeLibrary)//判断文件中是否存在同名ItemTypeLibrary
  57. {
  58. itemTypeLibrary = ItemTypeLibrary.Create(ITEMTYPELIB, m_dgnFile);//若不存在则进行创建
  59. }
  60. itemTypeLibrary.AddItemType(ITEMTYPE);//在ItemTypeLibrary中创建名为testItemTypeName的ItemType
  61. ItemType itemType = itemTypeLibrary.GetItemTypeByName(ITEMTYPE);//获取创建的ItemType
  62. CustomProperty intProperty = itemType.AddProperty(ITEMPROP);//对该ItemType添加名为IntProperty的属性
  63. intProperty.Type = CustomProperty.TypeKind.Integer;//设置IntProperty的属性类型
  64. intProperty.DefaultValue =10;//为StrProperty设置默认值,若不进行设置则默认为空
  65. bool result = itemTypeLibrary.Write();//将ItemTypeLibrary中的信息进行写入更新
  66. if (!result)//判断写入是否成功
  67. {
  68. MessageBox.Show("Input ItemType failure");//若成功输出输入ItemType成功的提示框
  69. return false;//返回结果
  70. }
  71. return true;//返回结果
  72. }
  73. private static Element CreateComplexSolid(int length)
  74. {
  75. DPoint3d p1 = new DPoint3d(10000, 10000);//定义截面轮廓线端点
  76. DPoint3d p2 = new DPoint3d(10000, -10000);
  77. DPoint3d p3 = new DPoint3d(-10000, -10000);
  78. DPoint3d p4 = new DPoint3d(-10000, 10000);
  79. IList<DPoint3d> pos = new List<DPoint3d>() { p1, p2, p3, p4 };//定义轮廓线端点数组
  80. CurveVector curve = CurveVector.CreateLinear(pos, CurveVector.BoundaryType.Outer, true);//定义轮廓线
  81. DVector3d vector = new DVector3d(0, 0, length * 10000);//定义拉伸向量(包含拉伸长度及方向信息)
  82. DgnExtrusionDetail detail = new DgnExtrusionDetail(curve, vector, true);
  83. /*
  84. * 定义拉伸信息
  85. * baseCurve:截面轮廓曲线
  86. * extrusionVector:拉伸信息
  87. * capped:若启用端盖则为真
  88. */
  89. SolidPrimitive solid = SolidPrimitive.CreateDgnExtrusion(detail);//使用拉伸信息定义实体
  90. BentleyStatus result = Create.BodyFromSolidPrimitive(out SolidKernelEntity entityOut, solid, m_dgnModel);//使用拉伸实体定义SolidKernelEntity
  91. result = Convert1.BodyToElement(out Element elem, entityOut, null, m_dgnModel);//将SolidKernelEntity转换为元素
  92. return elem;//返回元素
  93. }
  94. private static void Addin_XAttributeChangedEvent(AddIn sender, AddIn.XAttributeChangedEventArgs eventArgs)
  95. {
  96. //XATTRIBUTEID_ECXAttributes=22271和LINKAGEID_ECXAttributes = 22271
  97. if (eventArgs.Change ==AddIn.ChangeTrackKind.ReplaceXAttribute&&
  98. eventArgs.XAttribute.MajorId==22271&&
  99. eventArgs.XAttribute.MinorId == 0
  100. )//判断是否为EC属性修改触发的
  101. {
  102. Element elem = Element.GetFromElementRef(eventArgs.XAttribute.ElemRefPtr);//根据事件参数获得变换所属元素
  103. CustomItemHost host = new CustomItemHost(elem, true);//声明元素的CustomItemHost
  104. IList<IDgnECInstance>instances= host.CustomItems;//获得CustomItemHost的所有EC实例集
  105. foreach (IDgnECInstance instance in instances)//遍历EC实例集
  106. {
  107. IECPropertyValue propVal= instance.GetPropertyValue(ITEMPROP);//获得指定名称的属性
  108. if(propVal!=null)//判断是否成功获得
  109. {
  110. Element element = CreateComplexSolid(propVal.IntValue);
  111. element.ReplaceInModel(elem);//将元素写入模型
  112. }
  113. }
  114. }
  115. }
  116. }
  117. }

3.gif
图7 工程属性与元素几何联动