├── CodeSnippets.cs └── README.md /CodeSnippets.cs: -------------------------------------------------------------------------------- 1 | //============代码片段2-1:外部命令中Excute函数的定义============ 2 | public interface IExternalCommand 3 | { 4 | public Autodesk.Revit.UI.Result Execute( 5 | Autodesk.Revit.UI.ExternalCommandData commandData, 6 | ref string message, 7 | Autodesk.Revit.DB.ElementSet elements) 8 | } 9 | 10 | //============代码片段2-2:从commandData中取到Document============ 11 | UIApplication uiApplication = commandData.Application; 12 | Application application = uiApplication.Application; 13 | UIDocument uiDocument = uiApplication.ActiveUIDocument; 14 | Document document = uiDocument.Document; 15 | 16 | //============代码片段2-3:使用message参数============ 17 | public class command : IExternalCommand 18 | { 19 | public Result Execute( 20 | ExternalCommandData commandData, 21 | ref string message, 22 | ElementSet elements) 23 | { 24 | message = "message test"; 25 | return Result.Failed; 26 | } 27 | } 28 | 29 | //============代码片段2-4:使用element参数============ 30 | public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) 31 | { 32 | message = "Please take attention on the highlighted Walls!"; 33 | //先从UI选取元素,然后执行该插件 34 | ElementSet elems = commandData.Application.ActiveUIDocument.Selection.Elements; 35 | foreach (Element elem in elems) 36 | { 37 | Wall wall = elem as Wall; 38 | if (null != wall) 39 | { 40 | elements.Insert(elem); 41 | } 42 | } 43 | return Result.Failed; 44 | } 45 | 46 | //============代码片段2-5:外部命令中Excute函数的返回值============ 47 | public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) 48 | { 49 | try 50 | { 51 | UIDocument uiDoc = commandData.Application.ActiveUIDocument; 52 | Document doc = uiDoc.Document; 53 | List selectedElem = new List(); 54 | foreach(Element elem in uiDoc.Selection.Elements) 55 | { 56 | selectedElem.Add(elem.Id); 57 | } 58 | 59 | doc.Delete(selectedElem); 60 | 61 | TaskDialogResult result = TaskDialog.Show( 62 | "Revit", 63 | "Yes to return succeeded and delete all selection,"+ 64 | "No to cancel all commands.", 65 | TaskDialogCommonButtons.Yes|TaskDialogCommonButtons.No); 66 | 67 | if (TaskDialogResult.Yes == result) 68 | { 69 | return Result.Succeeded; 70 | } 71 | else if (TaskDialogResult.No == result) 72 | { 73 | elements = uiDoc.Selection.Elements; 74 | message = "Failed to delete selection."; 75 | return Result.Failed; 76 | } 77 | else 78 | { 79 | return Result.Cancelled; 80 | } 81 | } 82 | catch 83 | { 84 | message = "Unexpected Exception is thrown out."; 85 | return Result.Failed; 86 | } 87 | } 88 | 89 | //============代码片段2-6:IExternalApplication接口定义============ 90 | public interface IExternalApplication 91 | { 92 | Autodesk.Revit.UI.Result OnShutdown(UIControlledApplication application); 93 | Autodesk.Revit.UI.Result OnStartup(UIControlledApplication application); 94 | } 95 | 96 | //============代码片段2-7:使用IExternalApplication定制UI============ 97 | public Autodesk.Revit.UI.Result OnStartup(UIControlledApplication application) 98 | { 99 | //添加一个新的Ribbon面板 100 | RibbonPanel ribbonPanel = application.CreateRibbonPanel("NewRibbonPanel"); 101 | 102 | //在新的Ribbon面板上添加一个按钮 103 | //点击这个按钮,调用本章第四节第一个实例。 104 | PushButton pushButton = ribbonPanel.AddItem(new PushButtonData("HelloRevit", 105 | "HelloRevit", @"C:\Projects\HelloRevit\HelloRevit.dll", "HelloRevit.Class1")) as PushButton; 106 | return Result.Succeeded; 107 | } 108 | 109 | public Result OnShutdown(UIControlledApplication application) 110 | { 111 | //UI定制不需要特别在OnShutdown方法中做处理。 112 | return Result.Succeeded; 113 | } 114 | 115 | //============代码片段2-8:IExternalDBApplication接口定义============ 116 | public interface IExternalDBApplication 117 | { 118 | Autodesk.Revit.DB.ExternalDBApplicationResult OnShutdown(UIControlledApplication application); 119 | Autodesk.Revit.DB.ExternalDBApplicationResult OnStartup(UIControlledApplication application); 120 | } 121 | 122 | //============代码片段2-9:ExternalCommand的.addin文件格式示例============ 123 | 124 | 125 |    126 |     c:\MyProgram\MyProgram.dll 127 |     76eb700a-2c85-4888-a78d-31429ecae9ed 128 |     Revit.Samples.SampleCommand 129 |     Sample command 130 |     NotVisibleInFamily 131 |     NotVisibleInMEP 132 |     Revit.Samples.SampleAccessibilityCheck 133 |     

This is the long description for my command.

This is another descriptive paragraph, with notes about how to use the command properly.

134 |     c:\MyProgram\Autodesk.jpg 135 |     c:\MyProgram\MyProgramIcon.png 136 |     ADSK 137 |     Autodesk, www.autodesk.com 138 |    139 |
140 | 141 | //============代码片段2-10:ExternalApplication的.addin文件格式示例============ 142 | 143 | 144 |    145 |     SampleApplication 146 |     c:\MyProgram\MyProgram.dll 147 |     604B1052-F742-4951-8576-C261D1993107 148 |     Revit.Samples.SampleApplication 149 |     ADSK 150 |     Autodesk, www.autodesk.com 151 |    152 | 153 | 154 | //============代码片段2-11:数据库级别ExternalApplication的.addin文件格式示例============ 155 | 156 | 157 |     158 |       c:\MyDBLevelApplication\MyDBLevelApplication.dll 159 |       DA3D570A-1AB3-4a4b-B09F-8C15DFEC6BF0 160 |       MyCompany.MyDBLevelAddIn 161 |       My DB-Level AddIn 162 |       ADSK 163 |       Autodesk, www.autodesk.com 164 |     165 | 166 | 167 | //============代码片段2-12:外部命令中Excute函数的Transaction属性============ 168 | [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Automatic)] 169 | public class Class1 : IExternalCommand 170 | { 171 | } 172 | 173 | //============代码片段2-13:外部命令中Excute函数的Journaling属性============ 174 | [Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)] 175 | public class Class1 : IExternalCommand 176 | { 177 | } 178 | 179 | //============代码片段2-14:获取Application对象============ 180 | Autodesk.Revit.ApplicationServices.Application app 181 | = commandData.Application.Application; 182 | 183 | //============代码片段2-15:Revit版本及产品信息============ 184 | public void GetVersionInfo(Autodesk.Revit.ApplicationServices.Application app) 185 | { 186 | if (app.VersionNumber == "2014") 187 | { 188 | TaskDialog.Show("Supported version", 189 | "This application supported in this version."); 190 | } 191 | else 192 | { 193 | TaskDialog dialog = new TaskDialog("Unsupported version."); 194 | dialog.MainIcon = TaskDialogIcon.TaskDialogIconWarning; 195 | dialog.MainInstruction = "This application is only supported in Revit 2014."; 196 | dialog.Show(); 197 | } 198 | } 199 | 200 | //============代码片段2-16:获取UIApplication对象============ 201 | Autodesk.Revit.UI.UIpplication uiApp = commandData.Application; 202 | 203 | //============代码片段2-17:获取文档对象============ 204 | Autodesk.Revit.UI.UIDocument activeDoc = commandData.Application.ActiveUIDocument; 205 | Autodesk.Revit.DB.DocumentSet documents = commandData.Application.Application.Documents; 206 | 207 | //============代码片段2-18:从Setting中取到当前文档的Categories============ 208 | // 从当前文档对象中取到Setting对象 209 | Settings documentSettings = document.Settings; 210 | String prompt = "Number of all categories in current Revit document: " + documentSettings.Size+"\n"; 211 | 212 | // 用BuiltInCategory枚举值取到一个对应的Floor Category,打印其名字 213 | Category floorCategory = documentSettings.get_Item(BuiltInCategory.OST_Floors); 214 | prompt +="Get floor category and show the name: "; 215 | prompt += floorCategory.Name; 216 | 217 | TaskDialog.Show("Revit", prompt); 218 | 219 | //============代码片段2-19:使用Category ID============ 220 | Element selectedElement = null; 221 | foreach (Element e in document.Selection.Elements) 222 | { 223 | selectedElement = e; 224 | break; 225 | } 226 | // 取到当前元素的类别 227 | Category category = selectedElement.Category; 228 | BuiltInCategory enumCategory = (BuiltInCategory)category.Id.Value; 229 | 230 | //============代码片段2-20:打印当前文档中的可打印视图============ 231 | public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements) 232 | { 233 | Document doc = commandData.Application.ActiveUIDocument.Document; 234 | FilteredElementCollector collector = new FilteredElementCollector(doc).OfClass(typeof(ViewPlan)); 235 | IList viewElems = collector.ToElements(); 236 | ViewSet printableViews = new ViewSet(); 237 | 238 | // 找出全部可打印视图 239 | foreach (View view in viewElems) 240 | { 241 | if (!view.IsTemplate && view.CanBePrinted) 242 | { 243 | printableViews.Insert(view); 244 | } 245 | } 246 | PrintManager pm = doc.PrintManager; 247 | pm.PrintRange = PrintRange.Select; 248 | pm.SelectNewPrintDriver(@"\\server\printer01"); 249 | pm.Apply(); 250 | 251 | // 打印全部可打印视图 252 | doc.Print(printableViews); 253 | return IAsyncResult.Succeeded; 254 | } 255 | 256 | //============代码片段2-21:使用事务创建元素============ 257 | public void CreatingSketch(UIApplication uiApplication) 258 | { 259 | Document document = uiApplication.ActiveUIDocument.Document; 260 | ApplicationServices.Application application = uiApplication.Application; 261 | 262 | // 创建一些几何线,这些线是临时的,所以不需要放在事务中 263 | XYZ Point1 = XYZ.Zero; 264 | XYZ Point2 = new XYZ(10, 0, 0); 265 | XYZ Point3 = new XYZ(10, 10, 0); 266 | XYZ Point4 = new XYZ(0, 10, 0); 267 | 268 | Line geomLine1 = Line.CreateBound(Point1, Point2); 269 | Line geomLine2 = Line.CreateBound(Point4, Point3); 270 | Line geomLine3 = Line.CreateBound(Point1, Point4); 271 | 272 | // 这个几何平面也是临时的,不需要事务 273 | XYZ origin = XYZ.Zero; 274 | XYZ normal = new XYZ(0, 0, 1); 275 | Plane geomPlane = application.Create.NewPlane(normal, origin); 276 | 277 | // 为了创建SketchPlane,我们需要一个事务,因为这个会修改Revit文档模型 278 | 279 | // 任何Transaction要放在 “using”中创建 280 | // 来保证它被正确的结束,而不会影响到其他地方 281 | using (Transaction transaction = new Transaction(document)) 282 | { 283 | if (transaction.Start("Create model curves") == TransactionStatus.Started) 284 | { 285 | // 在当前文档中创建一个SketchPlane 286 | SketchPlane sketch = SketchPlane.Create(document, geomPlane); 287 | 288 | //使用SketchPlane和几何线来创建一个ModelLine 289 | ModelLine line1 = document.Create.NewModelCurve(geomLine1, sketch) as ModelLine; 290 | ModelLine line2 = document.Create.NewModelCurve(geomLine2, sketch) as ModelLine; 291 | ModelLine line3 = document.Create.NewModelCurve(geomLine3, sketch) as ModelLine; 292 | 293 | // 询问用户这个修改是否要提交 294 | TaskDialog taskDialog = new TaskDialog("Revit"); 295 | taskDialog.MainContent = "Click either [OK] to Commit, or [Cancel] to Roll back the transaction."; 296 | TaskDialogCommonButtons buttons = TaskDialogCommonButtons.Ok | TaskDialogCommonButtons.Cancel; 297 | taskDialog.CommonButtons = buttons; 298 | 299 | if (TaskDialogResult.Ok == taskDialog.Show()) 300 | { 301 | // 由于种种原因,如果修改或创建的模型不正确, 302 | // 这个Transaction可能不会被正确提交 303 | // 如果一个Transaction失败了或被用户取消了, 304 | // 那么返回的状态就是 RolledBack,而不是Committed。 305 | if (TransactionStatus.Committed != transaction.Commit()) 306 | { 307 | TaskDialog.Show("Failure", "Transaction could not be committed"); 308 | } 309 | } 310 | else 311 | { 312 | transaction.RollBack(); 313 | } 314 | } 315 | } 316 | } 317 | 318 | //============代码片段2-22:使用Assimilate方法============ 319 | public void CompoundOperation(Autodesk.Revit.DB.Document document) 320 | { 321 | // 所有TransactionGroup要用“using”来创建来保证它的正确结束 322 | using (TransactionGroup transGroup = new TransactionGroup(document, "Level and Grid")) 323 | { 324 | if (transGroup.Start() == TransactionStatus.Started) 325 | { 326 | // 我们打算调用两个函数,每个都有一个独立的事务 327 | // 我们打算这个组合操作要么成功,要么失败 328 | // 只要其中有一个失败,我们就撤销所有操作 329 | 330 | if (CreateLevel(document, 25.0) && CreateGrid(document, new XYZ(0, 0, 0), new XYZ(10, 0, 0))) 331 | { 332 | // Assimilate函数会将这两个事务合并成一个,并只显示TransactionGroup的名字 333 | // 在Undo菜单里 334 | transGroup.Assimilate(); 335 | } 336 | else 337 | { 338 | // 如果有一个操作失败了,我们撤销在这个事务组里的所有操作 339 | transGroup.RollBack(); 340 | } 341 | } 342 | } 343 | } 344 | 345 | public bool CreateLevel(Autodesk.Revit.DB.Document document, double elevation) 346 | { 347 | using (Transaction transaction = new Transaction(document, "Creating Level")) 348 | { 349 | // 必须启动事务来修改文档 350 | if (TransactionStatus.Started == transaction.Start()) 351 | { 352 | if (null != document.Create.NewLevel(elevation)) 353 | { 354 | return (TransactionStatus.Committed == transaction.Commit()); 355 | } 356 | // 如果不能创建层,撤销这个事务 357 | transaction.RollBack(); 358 | } 359 | } 360 | return false; 361 | } 362 | 363 | public bool CreateGrid(Autodesk.Revit.DB.Document document, XYZ p1, XYZ p2) 364 | { 365 | using (Transaction transaction = new Transaction(document, "Creating Grid")) 366 | { 367 | if (TransactionStatus.Started == transaction.Start()) 368 | { 369 | Line gridLine = Line.CreateBound(p1, p2); 370 | 371 | if ((null != gridLine) && (null != document.Create.NewGrid(gridLine))) 372 | { 373 | if (TransactionStatus.Committed == transaction.Commit()) 374 | { 375 | return true; 376 | } 377 | } 378 | // 如果不能创建网格,撤销这个事务 379 | transaction.RollBack(); 380 | } 381 | } 382 | return false; 383 | } 384 | 385 | //============代码片段2-23:HelloRevit============ 386 | using System; 387 | 388 | using Autodesk.Revit.UI; 389 | using Autodesk.Revit.DB; 390 | namespace HelloRevit 391 | { 392 | [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)] 393 | public class Class1 : IExternalCommand 394 | { 395 | public Autodesk.Revit.UI.Result Execute(ExternalCommandData revit, 396 | ref string message, ElementSet elements) 397 | { 398 | TaskDialog.Show("Revit", "Hello Revit"); 399 | return Autodesk.Revit.UI.Result.Succeeded; 400 | } 401 | } 402 | } 403 | 404 | //============代码片段2-24:HelloRevit.addin文件============ 405 | 406 | 407 | 408 | [dll文件所在路径]\HelloRevit.dll 409 | 7d4e1893-3a27-4df2-8075-4fa3754537aa 410 | HelloRevit.Class1 411 | ADSK 412 | 413 | 414 | 415 | //============代码片段2-25:插件抛出异常============ 416 | Command: IExternalCommand 417 | { 418 | public IExternalCommand.Result Execute () 419 | { 420 | //抛出异常… 421 | } 422 | } 423 | 424 | //============代码片段2-26:添加Ribbon面板============ 425 | using System; 426 | using System.Collections.Generic; 427 | using System.Linq; 428 | using System.Text; 429 | using System.Windows.Media.Imaging; 430 | 431 | using Autodesk.Revit.UI; 432 | using Autodesk.Revit.DB; 433 | 434 | namespace HelloRevit 435 | { 436 | public class CsAddpanel : Autodesk.Revit.UI.IExternalApplication 437 | { 438 | public Autodesk.Revit.UI.Result OnStartup(UIControlledApplication application) 439 | { 440 | //添加一个新的Ribbon面板 441 | RibbonPanel ribbonPanel = application.CreateRibbonPanel("NewRibbonPanel"); 442 | 443 | //在新的Ribbon面板上添加一个按钮 444 | //点击这个按钮,前一个例子“HelloRevit”这个插件将被运行。 445 | PushButton pushButton = ribbonPanel.AddItem(new PushButtonData("HelloRevit", 446 | "HelloRevit", @"C:\Projects\HelloRevit\HelloRevit.dll", "HelloRevit.Class1")) as PushButton; 447 | 448 | // 给按钮添加一个图片 449 | Uri uriImage = new Uri(@"C:\Projects\HelloRevit\logo.png"); 450 | BitmapImage largeImage = new BitmapImage(uriImage); 451 | pushButton.LargeImage = largeImage; 452 | 453 | return Result.Succeeded; 454 | } 455 | 456 | public Result OnShutdown(UIControlledApplication application) 457 | { 458 | return Result.Succeeded; 459 | } 460 | } 461 | } 462 | 463 | //============代码片段2-27:HelloRevit.addin文件============ 464 | 465 | 466 | 467 | C:\Projects\HelloRevit\HelloRevit.dll 468 | 6cdba932-c058-4ec1-b038-33ed590c41d3 469 | HelloRevit 470 | HelloRevit.CsAddpanel 471 | ADSK 472 | 473 | 474 | 475 | 476 | //============代码片段2-28:先选择元素后执行命令============ 477 | using System; 478 | using Autodesk.Revit.UI; 479 | using Autodesk.Revit.DB; 480 | using Autodesk.Revit.UI.Selection; 481 | namespace HelloRevit 482 | { 483 | [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Automatic)] 484 | public class Class1 : IExternalCommand 485 | { 486 | public Autodesk.Revit.UI.Result Execute(ExternalCommandData revit, 487 | ref string message, ElementSet elements) 488 | { 489 | 490 | try 491 | { 492 | //在执行该插件之前,先选择一些元素。本例中选择了四面墙,一条模型线,一条网格线,一个房间,一个房间标签。 493 | 494 | //取到当前文档。 495 | UIDocument uidoc = revit.Application.ActiveUIDocument; 496 | //取到当前文档的选择集。 497 | Selection selection = uidoc.Selection; 498 | ElementSet collection = selection.Elements; 499 | 500 | if (0 == collection.Size) 501 | { 502 | // 如果在执行该例子之前没有选择任何元素,则会弹出提示. 503 | TaskDialog.Show("Revit", "你没有选任何元素."); 504 | } 505 | else 506 | { 507 | String info = "所选元素类型为: "; 508 | foreach (Element elem in collection) 509 | { 510 | info += "\n\t" + elem.GetType().ToString(); 511 | } 512 | 513 | TaskDialog.Show("Revit", info); 514 | } 515 | } 516 | catch (Exception e) 517 | { 518 | message = e.Message; 519 | return Autodesk.Revit.UI.Result.Failed; 520 | } 521 | 522 | return Autodesk.Revit.UI.Result.Succeeded; 523 | } 524 | } 525 | } 526 | 527 | //============代码片段2-29:在运行外部命令过程中选取元素============ 528 | using System; 529 | using Autodesk.Revit.UI; 530 | using Autodesk.Revit.DB; 531 | using Autodesk.Revit.UI.Selection; 532 | namespace HelloRevit 533 | { 534 | [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Automatic)] 535 | public class Class1 : IExternalCommand 536 | { 537 | public Autodesk.Revit.UI.Result Execute(ExternalCommandData revit, 538 | ref string message, ElementSet elements) 539 | { 540 | 541 | try 542 | { 543 | Document document = revit.Application.ActiveUIDocument.Document; 544 | // 点选指定类型的元素。本例中指定的类型为元素整体。 545 | Reference pickedElemRef = this.Selection.PickObject(ObjectType.Element); 546 | // 通过引用取到选中的元素。 547 | Element elem = this.Document.GetElement(pickedElemRef.ElementId); 548 | String info = "所选元素类型为: "; 549 | info += "\n\t" + elem.GetType().ToString(); 550 | 551 | TaskDialog.Show("Revit", info); 552 | } 553 | catch (Exception e) 554 | { 555 | message = e.Message; 556 | return Autodesk.Revit.UI.Result.Failed; 557 | } 558 | 559 | return Autodesk.Revit.UI.Result.Succeeded; 560 | } 561 | } 562 | } 563 | 564 | //============代码片段2-30:通过过滤器取到元素============ 565 | using System; 566 | 567 | using Autodesk.Revit.UI; 568 | using Autodesk.Revit.DB; 569 | using Autodesk.Revit.UI.Selection; 570 | using System.Collections.Generic; 571 | namespace HelloRevit 572 | { 573 | [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Automatic)] 574 | public class Class1 : IExternalCommand 575 | { 576 | public Autodesk.Revit.UI.Result Execute(ExternalCommandData revit, 577 | ref string message, ElementSet elements) 578 | { 579 | try 580 | { 581 | Document document = revit.Application.ActiveUIDocument.Document; 582 | 583 | // 创建一个类过滤器来过滤出所有的FamilyInstance类的元素。 584 | ElementClassFilter familyInstanceFilter = new ElementClassFilter(typeof(FamilyInstance)); 585 | 586 | // 创建一个类别过滤器来过滤出所有的内建类型为OST_Doors的元素。 587 | ElementCategoryFilter doorsCategoryfilter = 588 | new ElementCategoryFilter(BuiltInCategory.OST_Doors); 589 | 590 | // 创建一个逻辑过滤器来组合前面两个过滤器,实现过滤出所有Door元素。 591 | LogicalAndFilter doorInstancesFilter = 592 | new LogicalAndFilter(familyInstanceFilter, doorsCategoryfilter); 593 | 594 | FilteredElementCollector collector = new FilteredElementCollector(document); 595 | ICollection doors = collector.WherePasses(doorInstancesFilter).ToElementIds(); 596 | 597 | String prompt = "The ids of the doors in the current document are:"; 598 | foreach (ElementId id in doors) 599 | { 600 | prompt += "\n\t" + id.IntegerValue; 601 | } 602 | 603 | TaskDialog.Show("Revit", prompt); 604 | 605 | } 606 | catch (Exception e) 607 | { 608 | message = e.Message; 609 | return Autodesk.Revit.UI.Result.Failed; 610 | } 611 | return Autodesk.Revit.UI.Result.Succeeded; 612 | } 613 | } 614 | } 615 | 616 | 617 | //============代码片段3-1通过Id获取元素============ 618 | ElementId levelId = new ElementId(30); 619 | Element element = RevitDoc.GetElement(levelId); 620 | Level level = element as Level; 621 | if(level != null) 622 | { 623 | //使用level 624 | } 625 | 626 | //============代码片段3-2 过滤所有外墙============ 627 | FilteredElementCollector filteredElements = new FilteredElementCollector(RevitDoc); 628 | ElementClassFilter classFilter = new ElementClassFilter(typeof(Wall)); 629 | filteredElements = filteredElements.WherePasses(classFilter); 630 | foreach (Wall wall in filteredElements) 631 | { 632 | // 获取墙类型“功能”参数,它用来指示墙是否为外墙。 633 | var functionParameter = wall.WallType.get_Parameter(BuiltInParameter.FUNCTION_PARAM); 634 | if (functionParameter != null && functionParameter.StorageType == StorageType.Integer) 635 | { 636 | if (functionParameter.AsInteger() == (int)WallFunction.Exterior) 637 | { 638 | // 使用wall 639 | } 640 | } 641 | } 642 | 643 | //============代码片段3-3 获取被选元素============ 644 | [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)] 645 | public class MyExternalCommand : Autodesk.Revit.UI.IExternalCommand 646 | { 647 | public Autodesk.Revit.UI.Result Execute(Autodesk.Revit.UI.ExternalCommandData commandData, 648 | ref string message, ElementSet elements) 649 | { 650 | if (commandData.Application.ActiveUIDocument != null) 651 | { 652 | foreach (Element selected in 653 | commandData.Application.ActiveUIDocument.Selection.Elements) 654 | { 655 | Wall wall = selected as Wall; 656 | if(wall != null) 657 | { 658 | //使用wall 659 | } 660 | } 661 | } 662 | return Autodesk.Revit.UI.Result.Succeeded; 663 | } 664 | } 665 | 666 | //============代码片段3-4 获取“长度”参数============ 667 | ParameterSet parameters = element.Parameters; 668 | foreach (Parameter parameter in parameters) 669 | { 670 | if(parameter.Definition.Name == "长度" && parameter.StorageType == StorageType.Double) 671 | { 672 | double length = parameter.AsDouble(); 673 | // 使用length 674 | break; 675 | } 676 | } 677 | 678 | 679 | //============代码片段3-5 使用BuiltInParameter获取长度============ 680 | Wall wall = null; 681 | Parameter parameterLength = wall.get_Parameter(BuiltInParameter.CURVE_ELEM_LENGTH); 682 | if (parameterLength != null && parameterLength.StorageType == StorageType.Double) 683 | { 684 | double length = parameterLength.AsDouble(); 685 | // 使用length 686 | } 687 | 688 | //============代码片段3-6 修改参数============ 689 | Parameter parameterBaseOffset = wall.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET); 690 | if (parameterBaseOffset != null && parameterBaseOffset.StorageType == StorageType.Double) 691 | { 692 | if (!parameterBaseOffset.IsReadOnly) 693 | { 694 | bool success = parameterBaseOffset.Set(10); 695 | if (!success) 696 | { 697 | // 更新错误报告 698 | } 699 | } 700 | else 701 | { 702 | // 参数是只读的 703 | } 704 | } 705 | 706 | //============代码片段3-7 获取共享参数============ 707 | // 打开共享参数文件 708 | DefinitionFile definitionFile = RevitApp.OpenSharedParameterFile(); 709 | // 获取参数组的集合 710 | DefinitionGroups groups = definitionFile.Groups; 711 | 712 | foreach (DefinitionGroup group in groups) 713 | { 714 | // 获取参数组内的参数定义 715 | foreach (Definition definition in group.Definitions) 716 | { 717 | string name = definition.Name; 718 | ParameterType type = definition.ParameterType; 719 | // 对参数定义的其他操作 720 | } 721 | } 722 | 723 | //============代码片段3-8 创建共享参数============ 724 | string sharedParametersFilename = @"C:\shared-parameters.txt"; 725 | string groupName = "MyGroup"; 726 | string definitionName = "MyDefinition"; 727 | ParameterType parameterType = ParameterType.Text; 728 | CategorySet categorySet = new CategorySet(); 729 | Category wallCategory = RevitDoc.Settings.Categories.get_Item(BuiltInCategory.OST_Walls); 730 | categorySet.Insert(wallCategory); 731 | bool instanceParameter = true; 732 | BuiltInParameterGroup parameterGroup = BuiltInParameterGroup.PG_DATA; 733 | 734 | if (!System.IO.File.Exists(sharedParametersFilename)) 735 | { 736 | try 737 | { 738 | System.IO.StreamWriter sw = System.IO.File.CreateText(sharedParametersFilename); 739 | sw.Close(); 740 | } 741 | catch (Exception) 742 | { 743 | throw new Exception("Can't create shared parameter file: " + sharedParametersFilename); 744 | } 745 | } 746 | // 设置共享参数文件 747 | RevitApp.SharedParametersFilename = sharedParametersFilename; 748 | 749 | // 打开共享参数文件 750 | DefinitionFile definitionFile = RevitApp.OpenSharedParameterFile(); 751 | if (definitionFile == null) 752 | { 753 | throw new Exception("Can not open shared parameter file!"); 754 | } 755 | 756 | // 获取参数组的集合 757 | DefinitionGroups groups = definitionFile.Groups; 758 | 759 | // 获取参数组 760 | DefinitionGroup group = groups.get_Item(groupName); 761 | if (null == group) 762 | { 763 | // 如果参数组不存在,则创建一个 764 | group = groups.Create(groupName); 765 | } 766 | if (null == group) 767 | throw new Exception("Failed to get or create group: " + groupName); 768 | 769 | // 获取参数定义 770 | Definition definition = group.Definitions.get_Item(definitionName); 771 | if (definition == null) 772 | { 773 | // 如果参数定义不存在,则创建一个 774 | definition = group.Definitions.Create(definitionName, parameterType); 775 | } 776 | 777 | // 调用不同的函数创建类型参数或者实例参数 778 | ElementBinding binding = null; 779 | if (instanceParameter) 780 | { 781 | binding = RevitApp.Create.NewInstanceBinding(categorySet); 782 | } 783 | else 784 | { 785 | binding = RevitApp.Create.NewTypeBinding(categorySet); 786 | } 787 | 788 | // 把参数定义和类别绑定起来(下面的小节会提到“绑定”),元素的新的参数就创建成功了。 789 | bool insertSuccess = RevitDoc.ParameterBindings.Insert(definition, binding, parameterGroup); 790 | 791 | if (!insertSuccess) 792 | { 793 | throw new Exception("Failed to bind definition to category"); 794 | } 795 | 796 | //============代码片段3-9 获取类别和参数的绑定============ 797 | BindingMap map = RevitDoc.ParameterBindings; 798 | DefinitionBindingMapIterator dep = map.ForwardIterator(); 799 | while (dep.MoveNext()) 800 | { 801 | Definition definition = dep.Key; 802 | // 获取参数定义的基本信息 803 | string definitionName = definition.Name; 804 | ParameterType parameterType = definition.ParameterType; 805 | // 几乎都可以转型为InstanceBinding,笔者没有碰到过其他情况,如有例外,请联系我们。 806 | InstanceBinding instanceBinding = dep.Current as InstanceBinding; 807 | if (instanceBinding != null) 808 | { 809 | // 获取绑定的类别列表 810 | CategorySet categorySet = instanceBinding.Categories; 811 | } 812 | } 813 | 814 | //============代码片段3-10 判断共享参数和项目参数============ 815 | Parameter parameter; 816 | InternalDefinition definition = parameter.Definition as InternalDefinition; 817 | 818 | bool isSharedParameter = parameter.IsShared; //共享参数 819 | 820 | bool isProjectParameter = definition.BuiltInParameter == BuiltInParameter.INVALID && !parameter.IsShared; //项目参数 821 | 822 | //============代码片段3-11 获取分析模型的几何信息============ 823 | Element element = RevitDoc.GetElement(new ElementId(183554)); 824 | if (element == null) return; 825 | AnalyticalModel analyticalModel = element.GetAnalyticalModel(); 826 | if(analyticalModel.IsSingleCurve()) 827 | { 828 | Curve curve = analyticalModel.GetCurve(); 829 | // work with curve 830 | } 831 | else if(analyticalModel.IsSinglePoint()) 832 | { 833 | XYZ p = analyticalModel.GetPoint(); 834 | // work with point 835 | } 836 | else 837 | { 838 | IList curves = analyticalModel.GetCurves(AnalyticalCurveType.ActiveCurves); 839 | // work with curves 840 | } 841 | 842 | //============代码片段3-12 放置类型为"0762 x 2032 mm"的门============ 843 | string doorTypeName = "0762 x 2032 mm"; 844 | FamilySymbol doorType = null; 845 | 846 | // 在文档中找到名字为"0762 x 2032 mm"的门类型 847 | ElementFilter doorCategoryFilter = new ElementCategoryFilter(BuiltInCategory.OST_Doors); 848 | ElementFilter familySymbolFilter = new ElementClassFilter(typeof(FamilySymbol)); 849 | LogicalAndFilter andFilter = new LogicalAndFilter(doorCategoryFilter, familySymbolFilter); 850 | FilteredElementCollector doorSymbols = new FilteredElementCollector(RevitDoc); 851 | doorSymbols = doorSymbols.WherePasses(andFilter); 852 | bool symbolFound = false; 853 | foreach (FamilySymbol element in doorSymbols) 854 | { 855 | if (element.Name == doorTypeName) 856 | { 857 | symbolFound = true; 858 | doorType = element; 859 | break; 860 | } 861 | } 862 | 863 | // 如果没有找到,就加载一个族文件 864 | if (!symbolFound) 865 | { 866 | string file = @"C:\ProgramData\Autodesk\RVT 2014\Libraries\Chinese_INTL\门\M_单-嵌板 4.rfa"; 867 | Family family; 868 | bool loadSuccess = RevitDoc.LoadFamily(file, out family); 869 | if (loadSuccess) 870 | { 871 | foreach (ElementId doorTypeId in family.GetValidTypes()) 872 | { 873 | doorType = RevitDoc.GetElement(doorTypeId) as FamilySymbol; 874 | if (doorType != null) 875 | { 876 | if (doorType.Name == doorTypeName) 877 | { 878 | break; 879 | } 880 | } 881 | } 882 | } 883 | else 884 | { 885 | Autodesk.Revit.UI.TaskDialog.Show("Load family failed", "Could not load family file '" + file + "'"); 886 | } 887 | } 888 | 889 | // 使用族类型创建门 890 | if (doorType != null) 891 | { 892 | // 首先找到线形的墙 893 | ElementFilter wallFilter = new ElementClassFilter(typeof(Wall)); 894 | FilteredElementCollector filteredElements = new FilteredElementCollector(RevitDoc); 895 | filteredElements = filteredElements.WherePasses(wallFilter); 896 | Wall wall = null; 897 | Line line = null; 898 | foreach (Wall element in filteredElements) 899 | { 900 | LocationCurve locationCurve = element.Location as LocationCurve; 901 | if (locationCurve != null) 902 | { 903 | line = locationCurve.Curve as Line; 904 | if (line != null) 905 | { 906 | wall = element; 907 | break; 908 | } 909 | } 910 | } 911 | 912 | // 在墙的中心位置创建一个门 913 | if (wall != null) 914 | { 915 | XYZ midPoint = (line.get_EndPoint(0) + line.get_EndPoint(1)) / 2; 916 | Level wallLevel = RevitDoc.GetElement(wall.LevelId) as Level; 917 | //创建门:传入标高参数,作为门的默认标高 918 | FamilyInstance door = RevitDoc.Create.NewFamilyInstance(midPoint, doorType, wall, wallLevel, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); 919 | Autodesk.Revit.UI.TaskDialog.Show("Succeed", door.Id.ToString()); 920 | Trace.WriteLine("Door created: " + door.Id.ToString()); 921 | } 922 | else 923 | { 924 | Autodesk.Revit.UI.TaskDialog.Show("元素不存在", "没有找到符合条件的墙"); 925 | } 926 | } 927 | else 928 | { 929 | Autodesk.Revit.UI.TaskDialog.Show("族类型不存在", "没有找到族类型'" + doorTypeName + "'"); 930 | } 931 | 932 | //============代码片段3-13 创建拉伸实体族============ 933 | //创建族文档 934 | Document familyDoc = RevitApp.NewFamilyDocument(@"C:\ProgramData\Autodesk\RVT 2014\Family Templates\Chinese\公制常规模型.rft"); 935 | using (Transaction transaction = new Transaction(familyDoc)) 936 | { 937 | transaction.Start("Create family"); 938 | CurveArray curveArray = new CurveArray(); 939 | curveArray.Append(Line.CreateBound(new XYZ(0, 0, 0), new XYZ(5, 0, 0))); 940 | curveArray.Append(Line.CreateBound(new XYZ(5, 0, 0), new XYZ(5, 5, 0))); 941 | curveArray.Append(Line.CreateBound(new XYZ(5, 5, 0), new XYZ(0, 5, 0))); 942 | curveArray.Append(Line.CreateBound(new XYZ(0, 5, 0), new XYZ(0, 0, 0))); 943 | CurveArrArray curveArrArray = new CurveArrArray(); 944 | curveArrArray.Append(curveArray); 945 | //创建一个拉伸实体 946 | familyDoc.FamilyCreate.NewExtrusion(true, curveArrArray, SketchPlane.Create(familyDoc, RevitApp.Create.NewPlane(new XYZ(0, 0, 1), XYZ.Zero)), 10); 947 | //创建一个族类型 948 | familyDoc.FamilyManager.NewType("MyNewType"); 949 | transaction.Commit(); 950 | familyDoc.SaveAs("MyNewFamily.rfa"); 951 | familyDoc.Close(); 952 | } 953 | 954 | //============代码片段3-14 复制墙类型============ 955 | Wall wall = RevitDoc.GetElement(new ElementId(185521)) as Wall; 956 | WallType wallType = wall.WallType; 957 | ElementType duplicatedWallType = wallType.Duplicate(wallType.Name + " (duplicated)"); 958 | 959 | //============代码片段3-15:元素编辑============ 960 | Document projectDoc = ActiveUIDocument.Document; 961 |             962 | using(Transaction moveColumnTran = new Transaction(projectDoc, "Move a new column to the new place")) 963 | { 964 |  moveColumnTran.Start(); 965 |                 966 |  // 获取Revit文档的创建句柄 967 |  Autodesk.Revit.Creation.Document creater = projectDoc.Create; 968 |  // 创建一根柱子:使用给定的位置(坐标原点),柱子类型和标高(高度为0) 969 |  XYZ origin = new XYZ(0, 0, 0); 970 |  Level level = GetALevel(projectDoc); 971 |  FamilySymbol columnType = GetAColumnType(projectDoc); 972 |  FamilyInstance column = creater.NewFamilyInstance(origin, columnType, level, Autodesk.Revit.DB.Structure.StructuralType.Column); 973 |  // 把柱子移动到新的位置 974 |  XYZ newPlace = new XYZ(10, 20, 30); 975 |  ElementTransformUtils.MoveElement(projectDoc, column.Id, newPlace); 976 |             977 |  moveColumnTran.Commit();        978 | } 979 | 980 | //============代码片段3-16:元素编辑============ 981 | Wall wall = element as Wall; 982 | if (null != wall) 983 | { 984 | LocationCurve wallLine = wall.Location as LocationCurve; 985 | XYZ newPlace = new XYZ(10, 20, 0); 986 | wallLine.Move(newPlace); 987 | } 988 | 989 | //============代码片段3-17:元素编辑============ 990 | using(Transaction tran = new Transaction(projectDoc, "Change the wall's curve with a new location line.")) 991 | { 992 |  tran.Start(); 993 |                 994 |  LocationCurve wallLine = wall.Location as LocationCurve; 995 |  XYZ p1 = XYZ.Zero; 996 |  XYZ p2 = new XYZ(10, 20, 0); 997 |  Line newWallLine = Line.CreateBound(p1, p2); 998 |  // 把墙的位置线换成新的线 999 |  wallLine.Curve = newWallLine; 1000 |              1001 |  tran.Commit(); 1002 | } 1003 | 1004 | //============代码片段3-18:元素编辑============ 1005 | FamilyInstance column = element as FamilyInstance; 1006 | if (null != column) 1007 | { 1008 | LocationPoint columnPoint = column.Location as LocationPoint; 1009 | XYZ newLocation = new XYZ(10, 20, 0); 1010 | // 移动柱子到新的位置(10,20,0) 1011 | columnPoint.Point = newLocation; 1012 | } 1013 | 1014 | //============代码片段3-19:元素编辑============ 1015 | using(Transaction tran = new Transaction(projectDoc, "Rotate the wall.")) 1016 | { 1017 |   tran.Start(); 1018 |   LocationCurve wallLine = wall.Location as LocationCurve; 1019 |   XYZ p1 = wallLine.Curve.GetEndPoint(0); 1020 |   XYZ p2 = new XYZ(p1.X, p1.Y, 30); 1021 |   Line axis = Line.CreateBound(p1, p2); 1022 |   ElementTransformUtils.RotateElement(projectDoc, wall.Id, axis, Math.PI / 3.0); 1023 |   tran.Commit(); 1024 | } 1025 | 1026 | //============代码片段3-20:元素编辑============ 1027 | Document projectDoc = ActiveUIDocument.Document; 1028 |              1029 | using(Transaction tran = new Transaction(projectDoc, "Rotate the wall and the column.")) 1030 | { 1031 |    tran.Start(); 1032 |                  1033 |    Wall wall = projectDoc.GetElement(new ElementId(184163)) as Wall; 1034 |                  1035 |    XYZ aa = XYZ.Zero; 1036 |    XYZ cc = XYZ.Zero; 1037 |    // 通过元素的位置线来旋转元素 1038 |    LocationCurve curve = wall.Location as LocationCurve; 1039 |    if (null != curve) 1040 |    { 1041 |        Curve line = curve.Curve; 1042 |        aa = line.GetEndPoint(0); 1043 |        cc = new XYZ(aa.X, aa.Y, aa.Z + 10); 1044 |        Line axis = Line.CreateBound(aa, cc); 1045 |        curve.Rotate(axis, Math.PI / 2.0); 1046 |    } 1047 |                  1048 |    FamilyInstance column = projectDoc.GetElement(new ElementId(184150)) as FamilyInstance; 1049 |                  1050 |    // 通过元素的位置点来旋转元素 1051 |    LocationPoint point = column.Location as LocationPoint; 1052 |    if (null != point) 1053 |    { 1054 |         aa = point.Point; 1055 |         cc = new XYZ(aa.X, aa.Y, aa.Z + 10); 1056 |         Line axis = Line.CreateBound(aa, cc); 1057 |         point.Rotate(axis, Math.PI / 3.0); 1058 |    } 1059 |    tran.Commit(); 1060 | } 1061 | 1062 | //============代码片段3-21:元素编辑============ 1063 | using(Transaction tran = new Transaction(projectDoc, "Mirror the column.")) 1064 | { 1065 |   tran.Start(); 1066 |                  1067 |   FamilyInstance column = projectDoc.GetElement(new ElementId(184150)) as FamilyInstance; 1068 |   if (null != column) 1069 |   { 1070 |      Plane plane = new Plane(XYZ.BasisX, XYZ.Zero); 1071 |      if(ElementTransformUtils.CanMirrorElement(projectDoc, column.Id)) 1072 |      { 1073 |         ElementTransformUtils.MirrorElement(projectDoc, column.Id, plane); 1074 |      } 1075 |   } 1076 |   tran.Commit(); 1077 | } 1078 | 1079 | //============代码片段3-22:元素编辑============ 1080 | Document projectDoc = ActiveUIDocument.Document; 1081 | Wall wall = projectDoc.GetElement(new ElementId(184163)) as Wall; 1082 | using(Transaction tran = new Transaction(projectDoc, "Delete the wall.")) 1083 | { 1084 |     tran.Start(); 1085 |     // 删除选择的元素:墙 1086 |     ICollection deletedElements = projectDoc.Delete(wall.Id); 1087 |     tran.Commit(); 1088 | } 1089 | 1090 | //============代码片段3-23:元素编辑============ 1091 | Document projectDoc = ActiveUIDocument.Document; 1092 | 1093 | List elementsToDelete = new List();             1094 |  using(Transaction tran = new Transaction(projectDoc, "Delete the selected elements.")) 1095 |  { 1096 |      tran.Start(); 1097 |      foreach (Element elem in ActiveUIDocument.Selection.Elements) 1098 |      { 1099 |          elementsToDelete.Add(elem.Id); 1100 |      } 1101 | 1102 |       ICollection deletedElements = projectDoc.Delete(elementsToDelete); 1103 |       tran.Commit(); 1104 |  } 1105 | 1106 | //============代码片段3-24:元素编辑============ 1107 | Document projectDoc = ActiveUIDocument.Document; 1108 | List elementsToGroup = new List(); 1109 | using(Transaction tran = new Transaction(projectDoc, "Group the selected elements.")) 1110 | { 1111 | tran.Start(); 1112 | foreach (Element elem in ActiveUIDocument.Selection.Elements) 1113 | { 1114 |    elementsToGroup.Add(elem.Id); 1115 | } 1116 | 1117 | Group group = projectDoc.Create.NewGroup(elementsToGroup); 1118 | tran.Commit(); 1119 | } 1120 | 1121 | //============代码片段3-25:元素编辑============ 1122 | // 把默认的组合名字改成新的名字:“MyGroup” 1123 | group.GroupType.Name = "MyGroup"; 1124 | 1125 | //============代码片段3-26:元素编辑============ 1126 | public void ArraryElements() 1127 |  { 1128 |     Document projectDoc = ActiveUIDocument.Document; 1129 |     Wall wall = projectDoc.GetElement(new ElementId(2307)) as Wall; 1130 |     using(Transaction tran = new Transaction(projectDoc, "LinearArray the wall.")) 1131 |     { 1132 |        tran.Start(); 1133 |        XYZ translation = new XYZ(0,10,0); 1134 |        LinearArray.Create(projectDoc, projectDoc.ActiveView, wall.Id, 3, translation, ArrayAnchorMember.Second); 1135 |        tran.Commit(); 1136 |      } 1137 |  } 1138 | 1139 | //============代码片段3-27:元素编辑============ 1140 | class projectFamLoadOption : IFamilyLoadOptions 1141 | { 1142 | bool IFamilyLoadOptions.OnFamilyFound(bool familyInUse, out bool overwriteParameterValues) 1143 | { 1144 | overwriteParameterValues = true; 1145 | return true; 1146 | } 1147 | bool IFamilyLoadOptions.OnSharedFamilyFound(Family sharedFamily, bool familyInUse, out FamilySource source, out bool overwriteParameterValues) 1148 | { 1149 | source = FamilySource.Project; 1150 | overwriteParameterValues = true; 1151 | return true; 1152 | } 1153 | }; 1154 | 1155 | //============代码片段3-28:元素编辑============ 1156 |  Document projectDoc = ActiveUIDocument.Document; 1157 | // 这里是自定义族实例,比如门,窗,桌子… 1158 | FamilyInstance famInst = elem as FamilyInstance; 1159 | // 编辑族,拿到族文档 1160 | Document familyDoc = projectDoc.EditFamily(famInst.Symbol.Family); 1161 | // 在族文档中添加一个新的参数 1162 | using(Transaction tran = new Transaction(projectDoc, "Edit family Document.")) 1163 | { 1164 |   tran.Start(); 1165 | string paramName = "MyParam "; 1166 | familyDoc.FamilyManager.AddParameter(paramName, BuiltInParameterGroup.PG_TEXT, ParameterType.Text, false); 1167 |   tran.Commit(); 1168 | } 1169 | // 将这些修改重新载入到工程文档中 1170 | Family loadedFamily = familyDoc.LoadFamily(RevitDoc, new projectFamLoadOption()); 1171 | 1172 | //============代码片段3-29:元素编辑============ 1173 | public void CreatReferencePlane() 1174 | { 1175 |    Document doc = this.ActiveUIDocument.Document;     1176 |    if(!doc.IsFamilyDocument) 1177 |       return; 1178 |              1179 |    using(Transaction transaction = new Transaction(doc, "Editing Family")) 1180 |    { 1181 |       transaction.Start(); 1182 |       XYZ bubbleEnd = new XYZ(0,5,5); 1183 |       XYZ freeEnd = new XYZ(5, 5, 5); 1184 |       XYZ cutVector = XYZ.BasisY; 1185 |       View view = doc.ActiveView; 1186 |       ReferencePlane referencePlane = doc.FamilyCreate.NewReferencePlane(bubbleEnd, freeEnd, cutVector, view); 1187 |       referencePlane.Name = "MyReferencePlane"; 1188 |       transaction.Commit();                 1189 |    } 1190 | } 1191 | 1192 | //============代码片段3-30:元素编辑============ 1193 | public void ChangeModelCurveToReferenceLine() 1194 | {             1195 |     Document doc = this.ActiveUIDocument.Document;     1196 |     ModelCurve modelCurve = doc.GetElement(new ElementId(2910)) as ModelCurve; 1197 |     using(Transaction transaction = new Transaction(doc, "Change model curve to reference line.")) 1198 |     { 1199 |         transaction.Start(); 1200 |         modelCurve.ChangeToReferenceLine(); 1201 |         transaction.Commit();                 1202 |     }             1203 | } 1204 | 1205 | //============代码片段3-31:元素编辑============ 1206 | public void CreateModelCurve() 1207 | { 1208 |    Document doc = this.ActiveUIDocument.Document;     1209 |    // 在族文档中找到名字为"Ref. Level"的标高 1210 |    FilteredElementCollector collector = new FilteredElementCollector(doc); 1211 |    collector = collector.OfCategory(BuiltInCategory.OST_Levels); 1212 |    var levelElements = from element in collector where element.Name == "Ref. Level" select element;   1213 |    List levels = levelElements.ToList();         1214 |    if(levels.Count <= 0) 1215 |       return;             1216 |    Level refLevel = levels[0] as Level; 1217 |              1218 |    // 创建一条几何直线,一个基于标高的草图平面,然后在这个草图平面上创建一条模型线. 1219 |    using(Transaction trans = new Transaction(doc, "Create model line.")) 1220 |    { 1221 |       trans.Start();     1222 |       Line line = Line.CreateBound(XYZ.Zero, new XYZ(10,10,0)); 1223 |       SketchPlane sketchPlane = SketchPlane.Create(doc, refLevel.Id);         1224 |       ModelCurve modelLine = doc.FamilyCreate.NewModelCurve(line, sketchPlane); 1225 | trans.Commit(); 1226 | } 1227 | } 1228 | 1229 | //============代码片段3-32:元素编辑============ 1230 | public void CreateSketchPlaneByPlane() 1231 | { 1232 |    Document doc = this.ActiveUIDocument.Document;     1233 |    using(Transaction trans = new Transaction(doc, "Create model arc.")) 1234 |    { 1235 |      trans.Start();     1236 |      Plane plane = this.Application.Create.NewPlane(XYZ.BasisZ, XYZ.Zero); 1237 |      SketchPlane sketchPlane = SketchPlane.Create(doc, plane); 1238 |              1239 |      Arc arc = Arc.Create(plane, 5, 0, Math.PI * 2); 1240 |      ModelCurve modelCircle = doc.FamilyCreate.NewModelCurve(arc, sketchPlane); 1241 |      trans.Commit(); 1242 |    } 1243 | } 1244 | 1245 | //============代码片段3-33:元素编辑============ 1246 | public void GetSketchFromExtrusion() 1247 | { 1248 |     Document doc = this.ActiveUIDocument.Document; 1249 |     Extrusion extrusion = doc.GetElement(new ElementId(3388)) as Extrusion; 1250 |     SketchPlane sketchPlane = extrusion.Sketch.SketchPlane; 1251 |     CurveArrArray sketchProfile = extrusion.Sketch.Profile; 1252 | } 1253 | 1254 | //============代码片段3-34:元素过滤器============ 1255 | FilteredElementCollector collection = new FilteredElementCollector(RevitDoc); 1256 | ElementFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_StackedWalls); 1257 | collection.OfClass(typeof(Wall)).WherePasses(filter); 1258 | ICollection foundIds = collection.ToElementIds(); 1259 | 1260 | //============代码片段3-35:元素过滤器============ 1261 | FilteredElementCollector collector = new FilteredElementCollector(m_doc); 1262 | // 查询并遍历文档中所有的Level 1263 | collector.WherePasses(new ElementCategoryFilter(BuiltInCategory.OST_Levels)).WhereElementIsNotElementType(); 1264 | foreach(Level level in collector) 1265 | { 1266 | TaskDialog.Show("Level Name", level.Name); 1267 | } 1268 | 1269 | //============代码片段3-36:元素过滤器============ 1270 | FilteredElementCollector collector = new FilteredElementCollector(m_doc); 1271 |   1272 | // 首先使用一个内建的过滤器来减少后面使用LINQ查询的元素数量 1273 | collector.WherePasses(new ElementCategoryFilter(BuiltInCategory.OST_Levels)); 1274 | 1275 | // LINQ查询:找到名字为"Level 1"的标高 1276 | var levelElements = from element in collector 1277 |                     where element.Name == "Level 1" 1278 |                     select element;   1279 | List levels = levelElements.ToList(); 1280 |   1281 | ElementId level1Id = levels[0].Id; 1282 | 1283 | //============代码片段3-37:元素过滤器============ 1284 | /// 1285 | /// 使用ElementCategoryFilter过滤元素 1286 | /// 1287 | void TestElementCategoryFilter(Document doc) 1288 | { 1289 | // 找到所有属于墙类别的元素:墙实例和墙类型都将会被过滤出来 1290 |    FilteredElementCollector collector = new FilteredElementCollector(doc); 1291 |    ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_Walls); 1292 |    ICollection founds = collector.WherePasses(filter).ToElements(); 1293 |    foreach (Element elem in founds) 1294 |    { 1295 |      Trace.WriteLine(String.Format("  Element id: {0}, type: {1}", elem.Id.IntegerValue, elem.GetType().Name)); 1296 |    } 1297 | } 1298 | 1299 | //============代码片段3-38:元素过滤器============ 1300 | /// 1301 | /// 使用ElementClassFilter过滤元素 1302 | /// 1303 | void TestElementClassFilter(Document doc) 1304 | { 1305 | // 找到所有属于FamilySymbol的元素:元素的子类也将被过滤出来 1306 |   FilteredElementCollector collector = new FilteredElementCollector(doc); 1307 |   ElementClassFilter filter = new ElementClassFilter(typeof(FamilySymbol)); 1308 |   ICollection founds = collector.WherePasses(filter).ToElementIds(); 1309 | Trace.WriteLine(String.Format("  Found {0} FamilySymbols.", founds.Count)); 1310 | } 1311 | 1312 | //============代码片段3-39:元素过滤器============ 1313 | /// 1314 | /// 使用ElementIsElementTypeFilter过滤元素 1315 | /// 1316 | void TestElementIsElementTypeFilter(Document doc) 1317 | { 1318 |   // 找到所有属于ElementType的元素 1319 |   FilteredElementCollector collector = new FilteredElementCollector(doc); 1320 |   ElementIsElementTypeFilter filter = new ElementIsElementTypeFilter(); 1321 |   ICollection founds = collector.WherePasses(filter).ToElementIds(); 1322 | Trace.WriteLine(String.Format("  Found {0} ElementTypes.", founds.Count)); 1323 | } 1324 | 1325 | //============代码片段3-40:元素过滤器============ 1326 | /// 1327 | /// 使用FamilySymbolFilter过滤元素 1328 | /// 1329 | void TestFamilySymbolFilter(Document doc) 1330 | { 1331 |   // 找到当前文档中族实例所对应的族类型 1332 |   FilteredElementCollector collector = new FilteredElementCollector(doc); 1333 |   ICollection famIds = collector.OfClass(typeof(Family)).ToElementIds(); 1334 |   foreach (ElementId famId in famIds) 1335 |   { 1336 |     collector = new FilteredElementCollector(doc); 1337 |     FamilySymbolFilter filter = new FamilySymbolFilter(famId); 1338 |     int count = collector.WherePasses(filter).ToElementIds().Count; 1339 |     Trace.WriteLine(String.Format("  {0} FamilySybmols belong to Family {1}.", count, famId.IntegerValue)); 1340 |   } 1341 | } 1342 | 1343 | //============代码片段3-41:元素过滤器============ 1344 | /// 1345 | /// 使用ExclusionFilter过滤元素 1346 | /// 1347 | void TestExclusionFilter(Document doc) 1348 | { 1349 |   // 找到所有除族类型FamilySymbol外的元素类型ElementType 1350 |   FilteredElementCollector collector = new FilteredElementCollector(doc); 1351 |   ICollection excludes = collector.OfClass(typeof(FamilySymbol)).ToElementIds(); 1352 |      1353 |   // 创建一个排除族类型FamilySymbol的过滤器 1354 |   ExclusionFilter filter = new ExclusionFilter(excludes); 1355 |   ICollection founds = collector.WhereElementIsElementType().WherePasses(filter).ToElementIds(); 1356 |   Trace.WriteLine(String.Format("  Found {0} ElementTypes which are not FamilySybmols", founds.Count)); 1357 | } 1358 | 1359 | //============代码片段3-42:元素过滤器============ 1360 | /// 1361 | /// 使用ElementLevelFilter过滤元素 1362 | /// 1363 | void TestElementLevelFilter(Document doc) 1364 | { 1365 |   // 找到当前所有标高对应的所有元素 1366 |   FilteredElementCollector collector = new FilteredElementCollector(doc); 1367 |   ICollection levelIds = collector.OfClass(typeof(Level)).ToElementIds(); 1368 |   foreach (ElementId levelId in levelIds) 1369 |   { 1370 |     collector = new FilteredElementCollector(doc); 1371 |     ElementLevelFilter filter = new ElementLevelFilter(levelId); 1372 |     ICollection founds = collector.WherePasses(filter).ToElementIds(); 1373 |     Trace.WriteLine(String.Format("  {0} Elements are associated to Level {1}.", founds.Count, levelId.IntegerValue)); 1374 |   } 1375 | } 1376 | 1377 | //============代码片段3-43:元素过滤器============ 1378 | /// 1379 | /// 使用ElementParameterFilter过滤元素 1380 | /// 1381 | void TestElementParameterFilter(Document doc) 1382 | { 1383 |   // 找到所有id大于99的元素 1384 |   BuiltInParameter testParam = BuiltInParameter.ID_PARAM; 1385 |   // 提供者 1386 |   ParameterValueProvider pvp = new ParameterValueProvider(new ElementId((int)testParam)); 1387 |   // 评估者 1388 |   FilterNumericRuleEvaluator fnrv = new FilterNumericGreater(); 1389 |   // 规则值    1390 |   ElementId ruleValId = new ElementId(99); // Id 大于 99 1391 |   // 创建规则过滤器及对应的元素参数过滤器 1392 |   FilterRule fRule = new FilterElementIdRule(pvp, fnrv, ruleValId); 1393 |   ElementParameterFilter filter = new ElementParameterFilter(fRule); 1394 |   FilteredElementCollector collector = new FilteredElementCollector(doc); 1395 |   ICollection founds = collector.WherePasses(filter).ToElements(); 1396 |   foreach (Element elem in founds) 1397 |   { 1398 |     Trace.WriteLine(String.Format("  Element id: {0}", elem.Id.IntegerValue)); 1399 |   } 1400 | } 1401 | 1402 | //============代码片段3-44:元素过滤器============ 1403 | /// 1404 | /// 使用FamilyInstanceFilter过滤元素 1405 | /// 1406 | void TestFamilyInstanceFilter(Document doc) 1407 | { 1408 |   // 找到名字"W10X49"的族类型 1409 |   FilteredElementCollector collector = new FilteredElementCollector(Document); 1410 |   collector = collector.OfClass(typeof(FamilySymbol)); 1411 |   var query = from element in collector 1412 |       where element.Name == "W10X49" 1413 |       select element; // Linq 查询 1414 |   List famSyms = query.ToList(); 1415 |   ElementId symbolId = famSyms[0].Id; 1416 |      1417 |   // 创建过滤器并找到该族类型对应的所有族实例 1418 |   collector = new FilteredElementCollector(doc); 1419 |   FamilyInstanceFilter filter = new FamilyInstanceFilter(doc, symbolId); 1420 |   ICollection founds = collector.WherePasses(filter).ToElements(); 1421 |   foreach (FamilyInstance inst in founds) 1422 |   { 1423 |     Trace.WriteLine(String.Format("  FamilyInstance {0}, FamilySybmol Id {1}, Name: {2}",inst.Id.IntegerValue, inst.Symbol.Id.IntegerValue, inst.Symbol.Name)); 1424 |   } 1425 | } 1426 | 1427 | //============代码片段3-45:元素过滤器============ 1428 |       /// /// 1429 | /// 使用CurveElementFilter 过滤元素 1430 | /// 1431 | void TestCurveElementFilter(Document doc) 1432 | { 1433 |     // 找到所有线元素类型对应的线型元素 1434 |     Array stTypes = Enum.GetValues(typeof(CurveElementType)); 1435 |     foreach (CurveElementType tstType in stTypes) 1436 |     { 1437 |         if (tstType == CurveElementType.Invalid) continue; 1438 |         FilteredElementCollector collector = new FilteredElementCollector(Document); 1439 |         CurveElementFilter filter = new CurveElementFilter(tstType); 1440 |         int foundNum = collector.WherePasses(filter).ToElementIds().Count; 1441 |         Trace.WriteLine(String.Format(" {0}: elements amount {1}", tstType.GetType().Name, foundNum)); 1442 |     } 1443 | } 1444 | 1445 | //============代码片段3-46:元素过滤器============ 1446 | /// 1447 | /// 使用LogicalOrFilter过滤元素 1448 | /// 1449 | void TestLogicalOrFilter(Document doc) 1450 | { 1451 |   // 情形 1: 合并两个过滤器 -> 1452 | // 找到所有属于墙类别或者属于标高类别的元素 1453 |   ElementCategoryFilter filterWall = new ElementCategoryFilter(BuiltInCategory.OST_Walls); 1454 |   ElementCategoryFilter filterLevel = new ElementCategoryFilter(BuiltInCategory.OST_Levels); 1455 |   LogicalOrFilter orFilter = new LogicalOrFilter(filterWall, filterLevel); 1456 |   FilteredElementCollector collector = new FilteredElementCollector(doc); 1457 |   ICollection founds = collector.WherePasses(orFilter).ToElements(); 1458 |   foreach(Element elem in founds) 1459 |   { 1460 |     Trace.WriteLine(String.Format("  Element Id {0}, type {1}", elem.Id.IntegerValue, elem.GetType())); 1461 |   } 1462 |      1463 |   // 情形 2: 合并两个过滤器集合 -> 找到所有属于传入类型的元素 1464 |   Type[] elemTypes = { typeof(Wall), typeof(Level), typeof(Floor), typeof(Rebar), typeof(MEPSystem)}; 1465 |   List filterSet = new List(); 1466 |   foreach (Type elemType in elemTypes) 1467 |   { 1468 |     ElementClassFilter filter = new ElementClassFilter(elemType); 1469 |     filterSet.Add(filter); 1470 |   } 1471 |   orFilter = new LogicalOrFilter(filterSet); 1472 |   collector = new FilteredElementCollector(doc); 1473 |   founds = collector.WherePasses(orFilter).ToElements(); 1474 |   foreach (Element elem in founds) 1475 |   { 1476 |     Trace.WriteLine(String.Format("  Element Id {0}, type {1}", elem.Id.IntegerValue, elem.GetType().Name)); 1477 |   } 1478 | } 1479 | 1480 | //============代码片段3-47:元素过滤器============ 1481 | /// 1482 | /// 使用LogicalAndFilter过滤器 1483 | /// 1484 | void TestLogicalAndFilter(Document doc) 1485 | { 1486 |   // 情形 1: 合并两个过滤器 -> 找到所有符合特定设计选项的墙 1487 |   ElementClassFilter wallFilter = new ElementClassFilter(typeof(Wall)); 1488 |   FilteredElementCollector collector = new FilteredElementCollector(doc); 1489 |   ICollection designOptIds = collector.OfClass(typeof(DesignOption)).ToElementIds(); 1490 |   foreach(ElementId curId in designOptIds) 1491 |   { 1492 |     ElementDesignOptionFilter designFilter = new ElementDesignOptionFilter(curId); 1493 |     LogicalAndFilter andFilter = new LogicalAndFilter(wallFilter, designFilter); 1494 |     collector = new FilteredElementCollector(doc); 1495 |     int wallCount = collector.WherePasses(andFilter).ToElementIds().Count; 1496 |     Trace.WriteLine(String.Format("  {0} Walls belong to DesignOption {1}.", wallCount, curId.IntegerValue)); 1497 |   } 1498 |      1499 |   // 情形 2: 找到所有符合特定设计选项并且其StructuralWallUsage 属于承重的墙 1500 |   foreach (ElementId curId in designOptIds) 1501 |   { 1502 |     // 构造逻辑与过滤器 1503 |     List filters = new List(); 1504 |     filters.Add(wallFilter); 1505 |     filters.Add(new ElementDesignOptionFilter(curId)); 1506 |     filters.Add(new StructuralWallUsageFilter(StructuralWallUsage.Bearing)); 1507 |     LogicalAndFilter andFilter = new LogicalAndFilter(filters); 1508 |          1509 |     // 应用该过滤器并遍历获取到的元素 1510 |     collector = new FilteredElementCollector(doc); 1511 |     int wallCount = collector.WherePasses(andFilter).ToElementIds().Count; 1512 |     Trace.WriteLine(String.Format("  {0} Bearing Walls belong to DesignOption {1}.", wallCount, curId.IntegerValue)); 1513 |   } 1514 | } 1515 | 1516 | //============代码片段3-48:元素过滤器============ 1517 | FilteredElementCollector collector = new FilteredElementCollector(document); 1518 | // 找到所有符合某种特定设计选项的墙 1519 | optionICollection walls = collector.OfClass(typeof(Wall)).ContainedInDesignOption(myDesignOptionId).ToElementIds(); 1520 | 1521 | //============代码片段4-1 修改标高的基面============ 1522 | LevelType levelType = RevitDoc.GetElement(level.GetTypeId()) as LevelType; 1523 | Parameter relativeBaseType = levelType.get_Parameter(BuiltInParameter.LEVEL_RELATIVE_BASE_TYPE); 1524 | relativeBaseType.Set(1); //项目基点 = 0, 测量点 = 1 1525 | 1526 | //============代码片段4-2 创建标高============ 1527 | using (Transaction transaction = new Transaction(RevitDoc)) 1528 | { 1529 | transaction.Start("Create Level"); 1530 | Level level = RevitDoc.Create.NewLevel(10.0); 1531 | transaction.Commit(); 1532 | } 1533 | 1534 | //============代码片段4-3 创建标高对应的视图============ 1535 | Level level; //已知的标高 1536 | //过滤出所有的ViewFamilyType 1537 | var classFilter = new ElementClassFilter(typeof(ViewFamilyType)); 1538 | FilteredElementCollector filteredElements = new FilteredElementCollector(RevitDoc); 1539 | filteredElements = filteredElements.WherePasses(classFilter); 1540 | foreach (ViewFamilyType viewFamilyType in filteredElements) 1541 | { 1542 | //找到ViewFamily类型是FloorPlan或者CeilingPlan的ViewFamilyType 1543 | if (viewFamilyType.ViewFamily == ViewFamily.FloorPlan || 1544 | viewFamilyType.ViewFamily == ViewFamily.CeilingPlan) 1545 | { 1546 | transaction.Start("Create view of type " + viewFamilyType.ViewFamily); 1547 | //创建视图 1548 | ViewPlan view = ViewPlan.Create(RevitDoc, viewFamilyType.Id, level.Id); 1549 | transaction.Commit(); 1550 | } 1551 | } 1552 | 1553 | //============代码片段4-4 创建轴网============ 1554 | using (Transaction transaction = new Transaction(RevitDoc)) 1555 | { 1556 | transaction.Start("Create Grid"); 1557 | Grid grid = RevitDoc.Create.NewGrid( 1558 | Line.CreateBound(new XYZ(0, 0, 0), new XYZ(10, 10, 0))); 1559 | grid.Name = "BB"; 1560 | transaction.Commit(); 1561 | } 1562 | 1563 | //============代码片段4-5 获取墙每层厚度和材质============ 1564 | Wall wall = GetElement(RevitDoc, new ElementId(732980)) as Wall; 1565 | CompoundStructure compoundStructure = wall.WallType.GetCompoundStructure(); 1566 | if (compoundStructure == null) 1567 | return; 1568 | if (compoundStructure.LayerCount > 0) 1569 | { 1570 | foreach (CompoundStructureLayer compoundStructureLayer in compoundStructure.GetLayers()) 1571 | { 1572 | //获取材质和厚度 1573 | ElementId materialId = compoundStructureLayer.MaterialId; 1574 | double layerWidth = compoundStructureLayer.Width; 1575 | } 1576 | } 1577 | 1578 | //============代码片段4-6 获取楼板的上表面============ 1579 | Floor floor = GetElement(185601); 1580 | 1581 | // 获取一个楼板面的引用 1582 | IList references = HostObjectUtils.GetTopFaces(floor); 1583 | if (references.Count == 1) 1584 | { 1585 | var reference = references[0]; 1586 | 1587 | // 从引用获取面的几何对象,这里是一个PlanarFace 1588 | GeometryObject topFaceGeo = floor.GetGeometryObjectFromReference(reference); 1589 | // 转型成我们想要的对象 1590 | PlanarFace topFace = topFaceGeo as PlanarFace; 1591 | } 1592 | 1593 | //============代码片段4-7 创建默认墙============ 1594 | ElementId levelId = new ElementId(311); 1595 | using (Transaction transaction = new Transaction(RevitDoc)) 1596 | { 1597 | transaction.Start("Create wall"); 1598 | Wall wall = Wall.Create(RevitDoc, Line.CreateBound(new XYZ(0, 0, 0), new XYZ(100, 0, 0)), levelId, false); 1599 | transaction.Commit(); 1600 | } 1601 | 1602 | //============代码片段4-8 创建梯形墙============ 1603 | IList curves = new List(); 1604 | curves.Add(Line.CreateBound(new XYZ(100, 20, 0), new XYZ(100, -20, 0))); 1605 | curves.Add(Line.CreateBound(new XYZ(100, -20, 0), new XYZ(100, -10, 10))); 1606 | curves.Add(Line.CreateBound(new XYZ(100, -10, 10), new XYZ(100, 10, 10))); 1607 | curves.Add(Line.CreateBound(new XYZ(100, 10, 5), new XYZ(100, 20, 0))); 1608 | using (Transaction transaction = new Transaction(RevitDoc)) 1609 | { 1610 | transaction.Start("Create wall"); 1611 | Wall wall = Wall.Create(RevitDoc, curves, false); 1612 | transaction.Commit(); 1613 | } 1614 | 1615 | //============代码片段4-9 创建正反两面墙============ 1616 | ElementId levelId = new ElementId(311); 1617 | ElementId wallTypeId = new ElementId(397); 1618 | IList curves = new List(); 1619 | 1620 | // 创建第一面墙 1621 | XYZ[] vertexes = new XYZ[] { new XYZ(0, 0, 0), new XYZ(0, 100, 0), new XYZ(0, 0, 100) }; 1622 | for (int ii = 0; ii < vertexes.Length; ii++) 1623 | { 1624 | if (ii != vertexes.Length - 1) 1625 | curves.Add(Line.CreateBound(vertexes[ii], vertexes[ii + 1])); 1626 | else 1627 | curves.Add(Line.CreateBound(vertexes[ii], vertexes[0])); 1628 | } 1629 | Wall wall = null; 1630 | using (Transaction transaction = new Transaction(RevitDoc)) 1631 | { 1632 | transaction.Start("Create wall 1"); 1633 | wall = Wall.Create(RevitDoc, curves, wallTypeId, levelId, false, new XYZ(-1, 0, 0)); 1634 | transaction.Commit(); 1635 | } 1636 | 1637 | // 创建第二面墙,面朝向相反 1638 | curves.Clear(); 1639 | vertexes = new XYZ[] { new XYZ(0, 0, 100), new XYZ(0, 100, 100), new XYZ(0, 100, 0) }; 1640 | for (int ii = 0; ii < vertexes.Length; ii++) 1641 | { 1642 | if (ii != vertexes.Length - 1) 1643 | curves.Add(Line.CreateBound(vertexes[ii], vertexes[ii + 1])); 1644 | else 1645 | curves.Add(Line.CreateBound(vertexes[ii], vertexes[0])); 1646 | } 1647 | using (Transaction transaction = new Transaction(RevitDoc)) 1648 | { 1649 | transaction.Start("Create wall 2"); 1650 | wall = Wall.Create(RevitDoc, curves, wallTypeId, levelId, false, new XYZ(1, 0, 0)); 1651 | transaction.Commit(); 1652 | } 1653 | 1654 | //============代码片段4-10 创建墙,并设置高度,偏移和是否翻转============ 1655 | ElementId levelId = new ElementId(311); 1656 | ElementId wallTypeId = new ElementId(397); 1657 | 1658 | using (Transaction transaction = new Transaction(RevitDoc)) 1659 | { 1660 | transaction.Start("Create wall"); 1661 | Wall wall = Wall.Create(RevitDoc, Line.CreateBound(new XYZ(0, 0, 0), new XYZ(0, 100, 0)), wallTypeId, levelId, 200, 300, true, false); 1662 | transaction.Commit(); 1663 | } 1664 | 1665 | //============代码片段4-11 创建三角形墙============ 1666 | CurveArray curveArray = new CurveArray(); 1667 | curveArray.Append(Line.CreateBound(new XYZ(0, 0, 0), new XYZ(100, 0, 0))); 1668 | curveArray.Append(Line.CreateBound(new XYZ(100, 0, 0), new XYZ(0, 100, 0))); 1669 | curveArray.Append(Line.CreateBound(new XYZ(0, 100, 0), new XYZ(0, 0, 0))); 1670 | using (Transaction transaction = new Transaction(RevitDoc)) 1671 | { 1672 | transaction.Start("Create floor"); 1673 | Floor floor = RevitDoc.Create.NewFloor(curveArray, false); 1674 | transaction.Commit(); 1675 | } 1676 | 1677 | //============代码片段4-12 创建屋顶============ 1678 | using (Transaction transaction = new Transaction(RevitDoc)) 1679 | { 1680 | View view = RevitDoc.ActiveView; 1681 | //先创建一个参照平面 1682 | XYZ bubbleEnd = new XYZ(0, 0, 0); 1683 | XYZ freeEnd = new XYZ(0, 100, 0); 1684 | XYZ thirdPnt = new XYZ(0, 0, 100); 1685 | transaction.Start("Create reference plane"); 1686 | ReferencePlane plane = 1687 | RevitDoc.Create.NewReferencePlane2(bubbleEnd, freeEnd, thirdPnt, view); 1688 | transaction.Commit(); 1689 | //创建屋顶前准备参数 1690 | Level level = RevitDoc.GetElement(new ElementId(311)) as Level; 1691 | RoofType roofType = RevitDoc.GetElement(new ElementId(335)) as RoofType; 1692 | CurveArray curveArray = new CurveArray(); 1693 | curveArray.Append(Line.CreateBound(new XYZ(0, 0, 50), new XYZ(0, 50, 100))); 1694 | curveArray.Append(Line.CreateBound(new XYZ(0, 50, 100), new XYZ(0, 100, 50))); 1695 | //创建屋顶 1696 | transaction.Start("Create roof"); 1697 | RevitDoc.Create.NewExtrusionRoof(curveArray, plane, level, roofType, 10, 200); 1698 | transaction.Commit(); 1699 | } 1700 | 1701 | //============代码片段4-13 创建带洞口屋顶============ 1702 | using (Transaction transaction = new Transaction(RevitDoc)) 1703 | { 1704 | //创建屋顶前准备参数 1705 | Level level = RevitDoc.GetElement(new ElementId(311)) as Level; 1706 | RoofType roofType = RevitDoc.GetElement(new ElementId(335)) as RoofType; 1707 | CurveArray curveArray = new CurveArray(); 1708 | //屋顶外边框 1709 | curveArray.Append(Line.CreateBound(new XYZ(0, 0, 0), new XYZ(30, 0, 0))); 1710 | curveArray.Append(Line.CreateBound(new XYZ(30, 0, 0), new XYZ(30, 30, 0))); 1711 | curveArray.Append(Line.CreateBound(new XYZ(30, 30, 0), new XYZ(0, 30, 0))); 1712 | curveArray.Append(Line.CreateBound(new XYZ(0, 30, 0), new XYZ(0, 0, 0))); 1713 | //在中间添加洞口 1714 | curveArray.Append(Line.CreateBound(new XYZ(5, 5, 0), new XYZ(5, 15, 0))); 1715 | curveArray.Append(Line.CreateBound(new XYZ(5, 15, 0), new XYZ(15, 5, 0))); 1716 | curveArray.Append(Line.CreateBound(new XYZ(15, 5, 0), new XYZ(5, 5, 0))); 1717 | 1718 | //创建屋顶 1719 | transaction.Start("Create roof"); 1720 | ModelCurveArray modelCurveArray = new ModelCurveArray(); 1721 | FootPrintRoof roof = 1722 | RevitDoc.Create.NewFootPrintRoof(curveArray, level, roofType, out modelCurveArray); 1723 | //设置屋顶坡度 1724 | ModelCurve curve1 = modelCurveArray.get_Item(0); 1725 | ModelCurve curve3 = modelCurveArray.get_Item(2); 1726 | roof.set_DefinesSlope(curve1, true); 1727 | roof.set_SlopeAngle(curve1, 0.5); 1728 | roof.set_DefinesSlope(curve3, true); 1729 | roof.set_SlopeAngle(curve3, 1.6); 1730 | transaction.Commit(); 1731 | } 1732 | 1733 | //============代码片段4-14 创建独立实例============ 1734 | // place a furniture at (0,0,0) 1735 | FamilySymbol familySymbol = RevitDoc.GetElement(new ElementId(99774)) as FamilySymbol; 1736 | using (Transaction transaction = new Transaction(RevitDoc)) 1737 | { 1738 | transaction.Start("Create standard-alone instance"); 1739 | FamilyInstance familyInstance = m_creation.NewFamilyInstance( 1740 | new XYZ(0, 0, 0), familySymbol, StructuralType.NonStructural); 1741 | transaction.Commit(); 1742 | Trace.WriteLine(familyInstance.Id); 1743 | } 1744 | 1745 | //============代码片段4-15 墙上创建门============ 1746 | // 在墙上创建一扇门 1747 | FamilySymbol familySymbol = RevitDoc.GetElement(new ElementId(49480)) as FamilySymbol; 1748 | Level level = RevitDoc.GetElement(new ElementId(30)) as Level; 1749 | Wall hostWall = RevitDoc.GetElement(new ElementId(180736)) as Wall; 1750 | using (Transaction transaction = new Transaction(RevitDoc)) 1751 | { 1752 | transaction.Start("Create standard-alone instance"); 1753 | FamilyInstance familyInstance = m_creation.NewFamilyInstance( 1754 | new XYZ(0, 0, 0), familySymbol, hostWall, level, StructuralType.NonStructural); 1755 | transaction.Commit(); 1756 | Trace.WriteLine(familyInstance.Id); 1757 | } 1758 | 1759 | //============代码片段4-16 创建柱子============ 1760 | // place a column at (0,0,0), 1761 | FamilySymbol familySymbol = RevitDoc.GetElement(new ElementId(52557)) as FamilySymbol; 1762 | Level level = RevitDoc.GetElement(new ElementId(331)) as Level; 1763 | using (Transaction transaction = new Transaction(RevitDoc)) 1764 | { 1765 | transaction.Start("Create a level based instance"); 1766 | FamilyInstance familyInstance = m_creation.NewFamilyInstance( 1767 | new XYZ(0, 0, 0), familySymbol, level, StructuralType.NonStructural); 1768 | transaction.Commit(); 1769 | Trace.WriteLine(familyInstance.Id); 1770 | } 1771 | 1772 | //============代码片段4-17 创建线形实例============ 1773 | // create a beam with an arc 1774 | FamilySymbol familySymbol = RevitDoc.GetElement(new ElementId(68912)) as FamilySymbol; 1775 | Level level = RevitDoc.GetElement(new ElementId(339)) as Level; 1776 | using (Transaction transaction = new Transaction(RevitDoc)) 1777 | { 1778 | transaction.Start("Create standard-alone instance"); 1779 | FamilyInstance familyInstance = m_creation.NewFamilyInstance( 1780 | Arc.Create(XYZ.Zero,10,0,2.5,new XYZ(1,0,0),new XYZ(0,1,0)), 1781 | familySymbol, level, StructuralType.Beam); 1782 | transaction.Commit(); 1783 | Trace.WriteLine(familyInstance.Id); 1784 | } 1785 | 1786 | //============代码片段4-18 创建二维实例============ 1787 | // 找到标题栏族类型 1788 | var titleBlockSymbols = new FilteredElementCollector(RevitDoc). 1789 | OfCategory(BuiltInCategory.OST_TitleBlocks).WhereElementIsElementType(); 1790 | FamilySymbol titleBlockSymbol = titleBlockSymbols.FirstElement() as FamilySymbol; 1791 | 1792 | // 获取一个ViewSheet 1793 | var viewSheet = RevitDoc.GetElement(new ElementId(175782)) as ViewSheet; 1794 | 1795 | // 在ViewSheet里面插入标题栏 1796 | using (Transaction transaction = new Transaction(RevitDoc)) 1797 | { 1798 | transaction.Start("插入标题栏"); 1799 | 1800 | var familyInstance = m_creation.NewFamilyInstance(XYZ.Zero, titleBlockSymbol, viewSheet); 1801 | 1802 | transaction.Commit(); 1803 | } 1804 | 1805 | //============代码片段4-19 创建二维线形实例============ 1806 | // 获取二维箭头族类型 1807 | FamilySymbol arrowSymbol = RevitDoc.GetElement(new ElementId(176135)) as FamilySymbol; 1808 | 1809 | // 找到一个二维视图 1810 | var viewPlans = new FilteredElementCollector(RevitDoc).OfClass(typeof(ViewPlan)).OfType(); 1811 | var viewPlan = viewPlans.FirstOrDefault(v => v.GenLevel != null); 1812 | var zPosition = viewPlan.GenLevel.Elevation; 1813 | // 创建族实例 1814 | using (Transaction transaction = new Transaction(RevitDoc)) 1815 | { 1816 | transaction.Start("NewFamilyInstance"); 1817 | 1818 | var familyInstance = m_creation.NewFamilyInstance( 1819 | Line.CreateBound(new XYZ(0, 0, zPosition), new XYZ(10, 10, zPosition)), 1820 | arrowSymbol, viewPlan); 1821 | Trace.WriteLine("Created family instance: " + familyInstance.Id); 1822 | 1823 | transaction.Commit(); 1824 | } 1825 | 1826 | //============代码片段4-20 创建基于面的族实例============ 1827 | // 获取类型 1828 | FamilySymbol arrowSymbol = RevitDoc.GetElement(new ElementId(574219)) as FamilySymbol; 1829 | 1830 | // 找到墙的一个面 1831 | var walls = new FilteredElementCollector(RevitDoc).OfClass(typeof(Wall)).OfType(); 1832 | var wall = walls.FirstOrDefault(); 1833 | var faceReferences = HostObjectUtils.GetSideFaces(wall, ShellLayerType.Exterior); 1834 | 1835 | // 创建实例 1836 | using (Transaction transaction = new Transaction(RevitDoc)) 1837 | { 1838 | transaction.Start("NewFamilyInstance"); 1839 | 1840 | var familyInstance = m_creation.NewFamilyInstance(faceReferences[0], 1841 | new XYZ(-51.659444225, 5.702513250, 10), new XYZ(0, 1, 1), arrowSymbol); 1842 | Trace.WriteLine("Created family instance: " + familyInstance.Id); 1843 | 1844 | transaction.Commit(); 1845 | } 1846 | 1847 | //============代码片段4-21 创建基于面的线形实例============ 1848 | // 获取类型 1849 | FamilySymbol stiffenerSymbol = RevitDoc.GetElement(new ElementId(97916)) as FamilySymbol; 1850 | 1851 | // 找到楼板的一个面 1852 | var floors = new FilteredElementCollector(RevitDoc).OfClass(typeof(Floor)).OfType(); 1853 | var floor = floors.FirstOrDefault(); 1854 | var faceReferences = HostObjectUtils.GetTopFaces(floor); 1855 | 1856 | // 创建实例 1857 | using (Transaction transaction = new Transaction(RevitDoc)) 1858 | { 1859 | transaction.Start("NewFamilyInstance"); 1860 | 1861 | var familyInstance = m_creation.NewFamilyInstance( 1862 | faceReferences[0], 1863 | Line.CreateBound(new XYZ(36, -40, 0), new XYZ(36, -20, 0)), 1864 | stiffenerSymbol); 1865 | Trace.WriteLine("Created family instance: " + familyInstance.Id); 1866 | 1867 | transaction.Commit(); 1868 | } 1869 | 1870 | //============代码片段4-22 批量创建人行道============ 1871 | // 创建一系列的人行道 1872 | 1873 | // 获取类型 1874 | FamilySymbol pavementSymbol = RevitDoc.GetElement(new ElementId(182412)) as FamilySymbol; 1875 | 1876 | // 准备创建数据 1877 | List list = new List(); 1878 | list.Add(new FamilyInstanceCreationData(new XYZ(10, 0, 0), pavementSymbol, StructuralType.NonStructural)); 1879 | list.Add(new FamilyInstanceCreationData(new XYZ(20, 0, 0), pavementSymbol, StructuralType.NonStructural)); 1880 | list.Add(new FamilyInstanceCreationData(new XYZ(30, 0, 0), pavementSymbol, StructuralType.NonStructural)); 1881 | list.Add(new FamilyInstanceCreationData(new XYZ(40, 0, 0), pavementSymbol, StructuralType.NonStructural)); 1882 | list.Add(new FamilyInstanceCreationData(new XYZ(50, 0, 0), pavementSymbol, StructuralType.NonStructural)); 1883 | 1884 | // 创建实例 1885 | using (Transaction transaction = new Transaction(RevitDoc)) 1886 | { 1887 | transaction.Start("Create pavements"); 1888 | var familyInstances = m_creation.NewFamilyInstances2(list); 1889 | transaction.Commit(); 1890 | foreach (var familyInstanceId in familyInstances) 1891 | { 1892 | Trace.WriteLine(familyInstanceId); 1893 | } 1894 | } 1895 | 1896 | //============代码片段4-23 创建房间============ 1897 | Level level; // 此处省略获取Level的代码 1898 | Phase phase; //此处省略获取Phase的代码 1899 | // 获取基于标高level的一个视图 1900 | var defaultView = new FilteredElementCollector(RevitDoc) 1901 | .WherePasses(new ElementClassFilter(typeof(View))) 1902 | .Cast() 1903 | .Where(v => v.GenLevel != null && v.GenLevel.Id == level.Id) 1904 | .FirstOrDefault(); 1905 | // 确保视图不为空 1906 | if (defaultView != null) 1907 | { 1908 | var defaultPhase = defaultView.get_Parameter(BuiltInParameter.VIEW_PHASE); 1909 | if (defaultPhase != null && defaultPhase.AsElementId() == phase.Id) 1910 | { 1911 | using (Transaction transaction = new Transaction(RevitDoc)) 1912 | { 1913 | transaction.Start("get_PlanTopology"); 1914 | var circuits = RevitDoc.get_PlanTopology(level, phase).Circuits; 1915 | transaction.Commit(); 1916 | foreach (PlanCircuit planCircuit in circuits) 1917 | { 1918 | RevitDoc.Create.NewRoom(null, planCircuit); 1919 | } 1920 | } 1921 | } 1922 | } 1923 | 1924 | //============代码片段4-24 创建面积============ 1925 | using (Transaction transaction = new Transaction(RevitDoc)) 1926 | { 1927 | transaction.Start("Create Area"); 1928 | //如果在点(30.0, 30.0)这个位置找不到面积边界,将会有警告对话框弹出。 1929 | Area area = RevitDoc.Create.NewArea(areaView, new UV(30.0, 30.0)); 1930 | transaction.Commit(); 1931 | } 1932 | 1933 | //============代码片段4-25 创建四方形闭合区域并在其上创建面积============ 1934 | using (Transaction transaction = new Transaction(RevitDoc)) 1935 | { 1936 | var create = RevitDoc.Create; 1937 | //通过创建四条面积边界线来形成一个正方形的闭合区域 1938 | transaction.Start("Create Area Boundary"); 1939 | var sketchPlane = areaView.SketchPlane; 1940 | create.NewAreaBoundaryLine(sketchPlane, 1941 | Line.CreateBound(new XYZ(20, 20, 0), new XYZ(40, 20, 0)), areaView); 1942 | create.NewAreaBoundaryLine(sketchPlane, 1943 | Line.CreateBound(new XYZ(40, 20, 0), new XYZ(40, 40, 0)), areaView); 1944 | create.NewAreaBoundaryLine(sketchPlane, 1945 | Line.CreateBound(new XYZ(40, 40, 0), new XYZ(20, 40, 0)), areaView); 1946 | create.NewAreaBoundaryLine(sketchPlane, 1947 | Line.CreateBound(new XYZ(20, 40, 0), new XYZ(20, 20, 0)), areaView); 1948 | transaction.Commit(); 1949 | 1950 | //在新创建的面积边界的中心点(30.0, 30.0)位置放置一个面积 1951 | transaction.Start("Create Area"); 1952 | Area area = create.NewArea(areaView, new UV(30.0, 30.0)); 1953 | transaction.Commit(); 1954 | } 1955 | 1956 | //============代码片段4-26 获取拓扑结构============ 1957 | using (Transaction transaction = new Transaction(RevitDoc)) 1958 | { 1959 | transaction.Start("GetPlanTopologies"); 1960 | PlanTopologySet planTopologies = RevitDoc.PlanTopologies; 1961 | transaction.Commit(); 1962 | } 1963 | 1964 | //============代码片段4-27 修改线样式============ 1965 | ICollection styles = modelCurve.GetLineStyleIds(); 1966 | foreach (ElementId styleId in styles) 1967 | { 1968 | if (styleId != modelCurve.LineStyle.Id) 1969 | { 1970 | using (Transaction transaction = new Transaction(RevitDoc)) 1971 | { 1972 | transaction.Start("Create Model Curve"); 1973 | modelCurve.LineStyle = RevitDoc.GetElement(styleId) as GraphicsStyle; 1974 | transaction.Commit(); 1975 | } 1976 | break; 1977 | } 1978 | } 1979 | 1980 | //============代码片段4-28 创建模型线============ 1981 | using (Transaction transaction = new Transaction(RevitDoc)) 1982 | { 1983 | transaction.Start("Create Model Line"); 1984 | Line geoLine = Line.CreateBound(XYZ.BasisY * 10, XYZ.BasisX * 10); 1985 | SketchPlane modelSketch = SketchPlane.Create(RevitDoc, RevitApp.Create.NewPlane(XYZ.BasisZ, XYZ.Zero)); 1986 | ModelCurve modelLine = RevitDoc.Create.NewModelCurve(geoLine, modelSketch); 1987 | transaction.Commit(); 1988 | } 1989 | 1990 | //============代码片段4-29 创建样条曲线============ 1991 | using (Transaction transaction = new Transaction(RevitDoc)) 1992 | { 1993 | SketchPlane modelSketch = SketchPlane.Create(RevitDoc, RevitApp.Create.NewPlane(XYZ.BasisZ, XYZ.Zero)); 1994 | transaction.Start("Create Model NurbSpline"); 1995 | NurbSpline nurbSpline = NurbSpline.Create( 1996 | new List { new XYZ(0, 0, 0), new XYZ(10, 0, 0), new XYZ(10, 10, 0), new XYZ(20, 10, 0), new XYZ(20, 20, 0) }, 1997 | new List { 0.5, 0.1, 0.3, 0.6, 0.8 }); 1998 | ModelCurve modelCurve = RevitDoc.Create.NewModelCurve(nurbSpline, modelSketch); 1999 | transaction.Commit(); 2000 | } 2001 | 2002 | //============代码片段4-30 获取洞口边界============ 2003 | if (opening.IsRectBoundary) 2004 | { 2005 | XYZ startPoint = opening.BoundaryRect[0]; 2006 | XYZ endPoint = opening.BoundaryRect[1]; 2007 | } else { 2008 | foreach (Curve curve in opening.BoundaryCurves) 2009 | { 2010 | //遍历Curve 2011 | } 2012 | } 2013 | 2014 | //============代码片段4-31 在墙上开洞口============ 2015 | Wall wall = GetElement(185520); 2016 | LocationCurve locationCurve = wall.Location as LocationCurve; 2017 | Line location = locationCurve.Curve as Line; 2018 | XYZ startPoint = location.get_EndPoint(0); 2019 | XYZ endPoint = location.get_EndPoint(1); 2020 | Parameter wallHeightParameter = wall.get_Parameter(BuiltInParameter.WALL_USER_HEIGHT_PARAM); 2021 | double wallHeight = wallHeightParameter.AsDouble(); 2022 | XYZ delta = (endPoint - startPoint + new XYZ(0, 0, wallHeight)) / 3; 2023 | 2024 | using (Transaction transaction = new Transaction(RevitDoc)) 2025 | { 2026 | transaction.Start("Create Opening on wall"); 2027 | Opening opening = RevitDoc.Create.NewOpening(wall, startPoint + delta, startPoint + delta * 2); 2028 | transaction.Commit(); 2029 | } 2030 | 2031 | //============代码片段5-1:创建线性尺寸标注============ 2032 | Transaction transaction = new Transaction(m_revit.Application.ActiveUIDocument.Document, "添加标注"); 2033 | transaction.Start(); 2034 | //取得墙,给墙的两个端点创建线性尺寸 2035 | for (int i = 0; i < m_walls.Count; i++) 2036 | { 2037 | Wall wallTemp = m_walls[i] as Wall; 2038 | if (null == wallTemp) 2039 | { 2040 | continue; 2041 | } 2042 | 2043 | //取得位置线 2044 | Location location = wallTemp.Location; 2045 | LocationCurve locationline = location as LocationCurve; 2046 | if (null == locationline) 2047 | { 2048 | continue; 2049 | } 2050 | 2051 | Line newLine = null; 2052 | 2053 | //取得参考 2054 | ReferenceArray referenceArray = new ReferenceArray(); 2055 | 2056 | AnalyticalModel analyticalModel = wallTemp.GetAnalyticalModel(); 2057 | IList activeCurveList = analyticalModel.GetCurves(AnalyticalCurveType.ActiveCurves); 2058 | foreach (Curve aCurve in activeCurveList) 2059 | { 2060 | // 从分析模型中找到不垂直的线 2061 | if (aCurve.GetEndPoint(0).Z == aCurve.GetEndPoint(1).Z) 2062 | newLine = aCurve as Line; 2063 | if (aCurve.GetEndPoint(0).Z != aCurve.GetEndPoint(1).Z) 2064 | { 2065 | AnalyticalModelSelector amSelector = new AnalyticalModelSelector(aCurve); 2066 | amSelector.CurveSelector = AnalyticalCurveSelector.StartPoint; 2067 | referenceArray.Append(analyticalModel.GetReference(amSelector)); 2068 | } 2069 | if (2 == referenceArray.Size) 2070 | break; 2071 | } 2072 | if (referenceArray.Size != 2) 2073 | { 2074 | m_errorMessage += "Did not find two references"; 2075 | return false; 2076 | } 2077 | try 2078 | { 2079 | //创建尺寸 2080 | Autodesk.Revit.UI.UIApplication app = m_revit.Application; 2081 | Document doc = app.ActiveUIDocument.Document; 2082 | 2083 | Autodesk.Revit.DB.XYZ p1 = new XYZ( 2084 | newLine.GetEndPoint(0).X + 5, 2085 | newLine.GetEndPoint(0).Y + 5, 2086 | newLine.GetEndPoint(0).Z); 2087 | Autodesk.Revit.DB.XYZ p2 = new XYZ( 2088 | newLine.GetEndPoint(1).X + 5, 2089 | newLine.GetEndPoint(1).Y + 5, 2090 | newLine.GetEndPoint(1).Z); 2091 | 2092 | Line newLine2 = Line.CreateBound(p1, p2); 2093 | Dimension newDimension = doc.Create.NewDimension( 2094 | doc.ActiveView, newLine2, referenceArray); 2095 | } 2096 | catch (Exception ex) 2097 | { 2098 | m_errorMessage += ex.ToString(); 2099 | return false; 2100 | } 2101 | } 2102 | transaction.Commit(); 2103 | 2104 | //============代码片段6-1:几何============ 2105 | public Options GetGeometryOption() 2106 | { 2107 | Autodesk.Revit.DB.Options option = this.Application.Create.NewGeometryOptions(); 2108 |   option.ComputeReferences = true; //打开计算几何引用 2109 |   option.DetailLevel = ViewDetailLevel.Fine; //视图详细程度为最好 2110 | return option; 2111 | } 2112 | 2113 | //============代码片段6-2:几何============ 2114 | public void GetWallGeometry() 2115 | { 2116 | Document doc = this.ActiveUIDocument.Document;         2117 | Wall aWall = doc.GetElement(new ElementId(186388)) as Wall; 2118 |              2119 | Options option = GetGeometryOption(); // 创建几何选项 2120 | Autodesk.Revit.DB.GeometryElement geomElement = aWall.get_Geometry(option); 2121 | foreach (GeometryObject geomObj in geomElement) 2122 | { 2123 |    Solid geomSolid = geomObj as Solid; 2124 |    if (null != geomSolid) 2125 |    { 2126 |       foreach (Face geomFace in geomSolid.Faces) 2127 |       { 2128 |          // 得到墙的面 2129 |       } 2130 |       foreach (Edge geomEdge in geomSolid.Edges) 2131 |       { 2132 |          // 得到墙的边 2133 |       } 2134 |    } 2135 | } 2136 | } 2137 | 2138 | //============代码片段6-3:几何============ 2139 | public void GetInstanceGeometry_Curve() 2140 | { 2141 | Document doc = this.ActiveUIDocument.Document;     2142 | FamilyInstance familyInstance = doc.GetElement(new ElementId(187032)) as FamilyInstance; 2143 | Options option = GetGeometryOption(); 2144 | Autodesk.Revit.DB.GeometryElement geomElement = familyInstance.get_Geometry(option); 2145 | 2146 | foreach (GeometryObject geomObj in geomElement) 2147 | { 2148 |    GeometryInstance geomInstance = geomObj as GeometryInstance; 2149 |    if (null != geomInstance) 2150 |    { 2151 |        foreach (GeometryObject instObj in geomInstance.SymbolGeometry) 2152 |        { 2153 |           Curve curve = instObj as Curve; 2154 |           if (null != curve) 2155 |           { 2156 |               // 把取到的线变换到实例的坐标系中 2157 |               curve = curve.CreateTransformed(geomInstance.Transform); 2158 |               // … 2159 |           } 2160 |         } 2161 |     } 2162 |  } 2163 | } 2164 | 2165 | //============代码片段6-4:几何============ 2166 | public void GetInstanceGeometry_Solid() 2167 | { 2168 | Document doc = this.ActiveUIDocument.Document; 2169 | FamilyInstance familyInstance = doc.GetElement(new ElementId(187758)) as FamilyInstance; 2170 | Options option = GetGeometryOption(); 2171 | Autodesk.Revit.DB.GeometryElement geomElement = familyInstance.get_Geometry(option); 2172 | 2173 | foreach (GeometryObject geomObj in geomElement) 2174 | { 2175 | GeometryInstance geomInstance = geomObj as GeometryInstance; 2176 | if (null != geomInstance) 2177 | { 2178 | foreach (GeometryObject instObj in geomInstance.SymbolGeometry) 2179 | { 2180 | Solid solid = instObj as Solid; 2181 | if (null == solid || 0 == solid.Faces.Size || 0 == solid.Edges.Size) 2182 | { 2183 | continue; 2184 | } 2185 | Transform instTransform = geomInstance.Transform; 2186 | // 从实体Solid获取面和边,然后对点进行变换 2187 | foreach (Face face in solid.Faces) 2188 | { 2189 | Mesh mesh = face.Triangulate(); 2190 | foreach (XYZ ii in mesh.Vertices) 2191 | { 2192 | XYZ point = ii; 2193 | XYZ transformedPoint = instTransform.OfPoint(point); 2194 | } 2195 | } 2196 | foreach (Edge edge in solid.Edges) 2197 | { 2198 | foreach (XYZ ii in edge.Tessellate()) 2199 | { 2200 | XYZ point = ii; 2201 | XYZ transformedPoint = instTransform.OfPoint(point); 2202 | } 2203 | } 2204 | } 2205 | } 2206 | } 2207 | } 2208 | 2209 | //============代码片段6-5:几何============ 2210 | public void DrawMesh() 2211 | { 2212 | Document doc = this.ActiveUIDocument.Document; 2213 | Transaction transaction = new Transaction(doc, "Draw Mesh"); 2214 | transaction.Start(); 2215 | 2216 | Sweep sweep = doc.GetElement(new ElementId(2311)) as Sweep; 2217 | Options option = GetGeometryOption(); 2218 | Autodesk.Revit.DB.GeometryElement geomElement = sweep.get_Geometry(option); 2219 | 2220 | foreach (GeometryObject geomObj in geomElement) 2221 | { 2222 | Solid geomSolid = geomObj as Solid; 2223 | if (null != geomSolid) 2224 | { 2225 | foreach (Face geomFace in geomSolid.Faces) 2226 | { 2227 | // 对面进行三角面片化形成一个网格 2228 | Mesh mesh = geomFace.Triangulate(); 2229 | for (int i = 0; i < mesh.NumTriangles; i++) 2230 | { 2231 | MeshTriangle triangular = mesh.get_Triangle(i); 2232 | // 定义 XYZ 列表来存放三角形的顶点 2233 | List triangularPoints = new List(); 2234 | for (int n = 0; n < 3; n++) 2235 | { 2236 | XYZ point = triangular.get_Vertex(n); 2237 | triangularPoints.Add(point); 2238 | } 2239 | // 调用方法把所有三角形在文档中描绘出来 2240 | DrawTriangle(doc, triangularPoints); 2241 | } 2242 | } 2243 | } 2244 | } 2245 | 2246 | transaction.Commit(); 2247 | } 2248 | 2249 | //============代码片段6-6:几何============ 2250 | // GeometryObject geoObj = GetGeometryObject(); 2251 | Solid solid = geoObj as Solid; 2252 | if(null != solid && 0 != solid.Faces.Size) 2253 | { 2254 | // 先判断再使用 2255 | } 2256 | 2257 | //============代码片段6-7:几何============ 2258 | public static XYZ TransformPoint(XYZ point, Transform transform) 2259 | { 2260 | double x = point.X; 2261 | double y = point.Y; 2262 | double z = point.Z; 2263 | //获取变换的原点和基向量 2264 | XYZ b0 = transform.get_Basis(0); 2265 | XYZ b1 = transform.get_Basis(1); 2266 | XYZ b2 = transform.get_Basis(2); 2267 | XYZ origin = transform.Origin; 2268 | //对原来坐标系统的点在新的坐标系统进行变换 2269 | double xTemp = x * b0.X + y * b1.X + z * b2.X + origin.X; 2270 | double yTemp = x * b0.Y + y * b1.Y + z * b2.Y + origin.Y; 2271 | double zTemp = x * b0.Z + y * b1.Z + z * b2.Z + origin.Z; 2272 | return new XYZ(xTemp, yTemp, zTemp); 2273 | } 2274 | 2275 | //============代码片段6-8:几何============ 2276 | // ReferencePlane refPlane = GetRefPlane(); 2277 |  Transform mirTrans = Transform.CreateReflection(refPlane.Plane); 2278 | 2279 | //============代码片段6-9:几何============ 2280 | Autodesk.Revit.DB.Options option = this.Application.Create.NewGeometryOptions(); 2281 | option.ComputeReferences = true; 2282 | option.DetailLevel = ViewDetailLevel.Medium; 2283 | 2284 | //============代码片段6-10:几何============ 2285 | public void ModifySectionBox() 2286 | {         2287 |   Document doc = this.ActiveUIDocument.Document;     2288 |   using(Transaction transaction = new Transaction(doc, "Modify Section Box")) 2289 |   { 2290 |     transaction.Start(); 2291 |                  2292 |     View3D view3d = doc.GetElement(new ElementId(186350)) as View3D;             2293 |     BoundingBoxXYZ box = view3d.GetSectionBox(); 2294 |     if (false == box.Enabled) 2295 |     { 2296 |       TaskDialog.Show("Error", "The section box for View3D isn't Enable."); 2297 |       return; 2298 |     } 2299 |     // 创建旋转变换 2300 |     XYZ origin = new XYZ(0, 0, 0); 2301 |     XYZ axis = new XYZ(0, 0, 1); 2302 |     Transform rotate = Transform.CreateRotationAtPoint(axis, 2, origin); 2303 |     // 把旋转变换应用于三维视图的剖面框 2304 |     box.Transform = box.Transform.Multiply(rotate); 2305 |     view3d.SetSectionBox(box); 2306 |                  2307 |     transaction.Commit(); 2308 |   } 2309 | } 2310 | 2311 | //============代码片段6-11:几何============ 2312 | Document projectDoc = ActiveUIDocument.Document; 2313 | View3D view = projectDoc.ActiveView as View3D; 2314 | if(view != null) 2315 | { 2316 |    BoundingBoxUV bbBoxUV = view.Outline; 2317 |    UV max = bbBoxUV.Max; 2318 |    UV min = bbBoxUV.Min; 2319 | } 2320 | 2321 | //============代码片段6-12:几何============ 2322 | //[in]geomElement, [out]curves, [out]solids 2323 | public void GetCurvesFromABeam(FamilyInstance beam, Options options, CurveArray curves, SolidArray solids) 2324 | { 2325 |   Autodesk.Revit.DB.GeometryElement geomElement = beam.get_Geometry(options); 2326 |   //找到所有的实体solids和线curves 2327 |   AddCurvesAndSolids(geomElement, curves, solids); 2328 | } 2329 | 2330 | private void AddCurvesAndSolids(GeometryElement geomElem, CurveArray curves, SolidArray solids) 2331 | { 2332 |   foreach (GeometryObject geomObject in geomElem) 2333 |   { 2334 |     Curve curve = geomObject  as Curve; 2335 |     if (null != curve) 2336 |     { 2337 |       curves.Append(curve); 2338 |       continue; 2339 |     } 2340 |     Solid solid = geomObject  as Solid; 2341 |     if (null != solid) 2342 |     { 2343 |       solids.Append(solid); 2344 |       continue; 2345 |     } 2346 |     //如果GeometryObject 是几何实例,则进行二次遍历 2347 |     GeometryInstance geomInst = geomObject  as GeometryInstance; 2348 |     if (null != geomInst) 2349 |     { 2350 |       AddCurvesAndSolids(geomInst.GetSymbolGeometry(geomInst.Transform), curves, solids); 2351 |     } 2352 |   } 2353 | } 2354 | 2355 | //============代码片段7-1 获取族管理器============ 2356 | Document doc; // 得到族文档 2357 | if(doc.IsFamilyDocument) 2358 | { 2359 | // 只有当IsFamilyDocument等于true, FamilyManager才能得到 2360 | FamilyManager familyMgr = doc.FamilyManager; 2361 | } 2362 | 2363 | //============代码片段7-2 获取当前族类型============ 2364 | //得到FamilyManager 2365 | FamilyManager familyMgr = doc.FamilyManager; 2366 | FamilyType currentType = familyMgr.CurrentType; 2367 | if(currentType != null) 2368 | { 2369 | //当前族类型可能为空,建议在其他操作前加上空检查 2370 | } 2371 | 2372 | //============代码片段7-3 创建新的类型============ 2373 | // 得到FamilyManager 2374 | FamilyManager familyMgr = doc.FamilyManager; 2375 | // 族类型的名字,保证在所有族类型中唯一 2376 | string newTypeName = "UniqueName"; 2377 | // 创建,得到FamilyType的实例 2378 | FamilyType famType = familyMgr.NewType(newTypeName); 2379 | 2380 | //============代码片段7-4 删除族类型============ 2381 | // 得到FamilyManager 2382 | FamilyManager familyMgr = doc.FamilyManager; 2383 | if(familyMgr.CurrentType != null) 2384 | { 2385 | // 只有当前族类型存在,我们才能调用下面的删除方法 2386 | familyMgr.DeleteCurrentType(); 2387 | // 一般来说,当删除结束后,第一个族类型会成为当前类型, 2388 | // 但是为了确保安全, 建议你显式设置成你需要的类型 2389 | if (familyMgr.Types.Size != 0) 2390 | { 2391 | FamilyType type = familyMgr.Types.Cast().ElementAt(0); 2392 | familyMgr.CurrentType = type; 2393 | } 2394 | } 2395 | 2396 | //============代码片段7-5 族类型重命名============ 2397 | // 得到FamilyManager 2398 | FamilyManager familyMgr = doc.FamilyManager; 2399 | // 族类型的名字,保证在所有族类型中唯一 2400 | string newTypeName = "UniqueName"; 2401 | familyMgr.RenameCurrentType(newTypeName); 2402 | 2403 | //============代码片段7-6 创建共享族参数============ 2404 | Autodesk.Revit.ApplicationServices.Application app; // 得到Application 2405 | // 得到FamilyManager 2406 | FamilyManager familyMgr = doc.FamilyManager; 2407 | 2408 | // 共享参数的基本信息, 包括定义文件路径,参数分组名称,参数名称和参数类型。 2409 | string sharedParameterFilePath = @"C:\SharedParameter.txt"; 2410 | string sharedParameterGroupName = "Shared_Group"; 2411 | string sharedParameter = "Shared_Parameter"; 2412 | ParameterType sharedParameterType = ParameterType.Length; 2413 | 2414 | // 打开或创建共享参数定义文件。 2415 | app.SharedParametersFilename = sharedParameterFilePath; 2416 | DefinitionFile sharedDefinitonFile = app.OpenSharedParameterFile(); 2417 | if (sharedDefinitonFile == null) 2418 | return; 2419 | 2420 | // 查找共享参数的分组名称,如果没找到,就创建一个。 2421 | DefinitionGroup sharedGroup = null; 2422 | sharedGroup = sharedDefinitonFile.Groups.get_Item(sharedParameterGroupName); 2423 | if (null == sharedGroup) 2424 | sharedGroup = sharedDefinitonFile.Groups.Create(sharedParameterGroupName); 2425 | 2426 | // 查找共享参数的定义,如果没有找到,就用名字和类型创建一个。 2427 | ExternalDefinition parameterDef = sharedGroup.Definitions.get_Item(sharedParameter) as ExternalDefinition; 2428 | if (null == parameterDef) 2429 | parameterDef = sharedGroup.Definitions.Create(sharedParameter, sharedParameterType) as ExternalDefinition; 2430 | 2431 | // 创建共享族参数 2432 | FamilyParameter newParameter = familyMgr.AddParameter(parameterDef, BuiltInParameterGroup.PG_CONSTRAINTS, true); 2433 | 2434 | //============代码片段7-7 创建一般族参数============ 2435 | // 得到FamilyManager 2436 | FamilyManager familyMgr = doc.FamilyManager; 2437 | string paraName = "UniqueName"; // 唯一 2438 | // 设置族参数的类别和类型 2439 | BuiltInParameterGroup paraGroup = BuiltInParameterGroup.PG_LENGTH; 2440 | ParameterType paraType = ParameterType.Length; 2441 | // 设置族参数为实例参数 2442 | bool isInstance = true; 2443 | // 创建族参数 2444 | FamilyParameter newParameter = familyMgr.AddParameter(paraName, paraGroup, paraType, isInstance); 2445 | 2446 | //============代码片段7-8 创建族类型参数============ 2447 | // 得到FamilyManager 2448 | FamilyManager familyMgr = doc.FamilyManager; 2449 | string paraName = "族类型参数"; // 唯一 2450 | BuiltInParameterGroup paraGroup = BuiltInParameterGroup.PG_TEXT; 2451 | // 设置族参数为实例参数 2452 | bool isInstance = true; 2453 | 2454 | // 得到一个已加载的族类型(FamilySymbol)的组。 2455 | FilteredElementCollector cotr = new FilteredElementCollector(doc); 2456 | IList symbols = cotr.OfClass(typeof(FamilySymbol)).ToElements(); 2457 | if (symbols.Count == 0) 2458 | return; // 未找到族类型,跳过创建 2459 | Category famCategory = symbols[0].Category; 2460 | 2461 | // 创建族参数 2462 | FamilyParameter newParameter = familyMgr.AddParameter(paraName, paraGroup, famCategory, isInstance); 2463 | 2464 | //============代码片段7-9 设置族参数公式============ 2465 | /// 2466 | /// 这个方法演示如何创建族参数的公式。 2467 | /// 包括了如下几种类型的族参数:长度,面积,体积和字符串类型。 2468 | /// 2469 | public void SetParameterFormula( 2470 | FamilyManager familyMgr, FamilyParameter lengthPara, 2471 | FamilyParameter areaPara, FamilyParameter volumePara, 2472 | FamilyParameter commentPara) 2473 | { 2474 | // 字符串类型的族参数的公式,必须要带上"" 2475 | familyMgr.SetFormula(commentPara, "\"注释内容\""); 2476 | 2477 | // 有单位的族参数(例如:长度类型)的公式,应该带上单位 2478 | familyMgr.SetFormula(lengthPara, "1000mm"); 2479 | 2480 | // 族参数的公式需要符合其类型的定义 2481 | // 例如面积类型的参数可以是2个长度参数的乘积 2482 | string lengtthParaName = lengthPara.Definition.Name; 2483 | familyMgr.SetFormula(areaPara, lengtthParaName + " * " + lengtthParaName); 2484 | 2485 | // 而体积类型的参数可以是3个长度参数的乘积 2486 | familyMgr.SetFormula(volumePara, lengtthParaName 2487 | + " * " + lengtthParaName + " * " + lengtthParaName); 2488 | } 2489 | 2490 | //============代码片段7-10 设置族参数的值============ 2491 | public void SetFamilyParameterValue( 2492 | FamilyManager familyMgr, FamilyParameter lengthPara, 2493 | FamilyParameter commentPara, FamilyParameter IntPara, 2494 | FamilyParameter materialPara, ElementId newMaterialId) 2495 | { 2496 | // 首先需要判断当前族类型是否存在,如果不存在,读写族参数都是不可行的 2497 | FamilyType currentType = familyMgr.CurrentType; 2498 | if (null == currentType) 2499 | return; 2500 | 2501 | // 读写长度类型的族参数;他的储存类型为double 2502 | double length = currentType.AsDouble(lengthPara).Value; 2503 | familyMgr.Set(lengthPara, length + 1.25); 2504 | 2505 | // 读写文字类型的族参数;他的储存类型为string 2506 | string comment = currentType.AsString(commentPara); 2507 | familyMgr.Set(commentPara, "新的注释"); 2508 | 2509 | // 读写整数类型的族参数;他的储存类型为int 2510 | int integerVale = currentType.AsInteger(IntPara).Value; 2511 | familyMgr.Set(IntPara, integerVale + 3); 2512 | 2513 | // 读写材质类型的族参数;他的储存类型为ElementId 2514 | ElementId materialId = currentType.AsElementId(materialPara); 2515 | familyMgr.Set(materialPara, newMaterialId); 2516 | 2517 | // 您可以读写族参数的可视化文字表示的值 2518 | string lengthText = currentType.AsValueString(lengthPara); 2519 | familyMgr.SetValueString(lengthPara, "10m"); 2520 | } 2521 | 2522 | //============代码片段7-11 关联族参数============ 2523 | public void AssociateParametersInFamilyDocument(FamilyManager familyMgr, 2524 | Parameter lengthElementPara, // 长度类型的图元参数 2525 | FamilyParameter lengthFamilyPara // 长度类型的族参数 2526 | ) 2527 | { 2528 | ParameterType lengthElementParaType = lengthElementPara.Definition.ParameterType; 2529 | ParameterType lengthFamilyParaType = lengthFamilyPara.Definition.ParameterType; 2530 | 2531 | // 能关联起来的图元参数和族参数的类型要相同 2532 | if (lengthElementParaType != lengthFamilyParaType) 2533 | { 2534 | // 注意:有些类型不同的图元参数和族参数也是可以关联的。 2535 | // 比如PipeSize和Length类型的参数可以关联,因为他们代表了相同的物理量:长度 2536 | return; 2537 | } 2538 | 2539 | // 判断该长度单位是否能够和族参数关联 2540 | if (!familyMgr.CanElementParameterBeAssociated(lengthElementPara)) 2541 | return; 2542 | 2543 | // 进行关联操作 2544 | familyMgr.AssociateElementParameterToFamilyParameter(lengthElementPara, lengthFamilyPara); 2545 | } 2546 | 2547 | //============代码片段7-12 关联族参数和尺寸标注============ 2548 | public void AssociateParameterToDimension( 2549 | Dimension dimension, FamilyParameter familyPara) 2550 | { 2551 | // 获取当前关联的族参数 2552 | FamilyParameter currentPara = dimension.FamilyLabel; 2553 | if(null != currentPara) 2554 | { 2555 | // 新关联的族参数类型应该和现有的族参数类型一致。 2556 | // 就像上个例子提到的一样,他们至少应该是物理意义相同。 2557 | if (currentPara.Definition.ParameterType != familyPara.Definition.ParameterType) 2558 | return; 2559 | } 2560 | 2561 | // 关联新的族参数 2562 | dimension.FamilyLabel = familyPara; 2563 | 2564 | // 清空关联 2565 | dimension.FamilyLabel = null; 2566 | } 2567 | 2568 | //============代码片段7-13 创建拉伸体============ 2569 | private Application m_revit; // 已获得Revit的Application的实例 2570 | private Document m_familyDocument; // 已获得族文档的实例 2571 | // 创建工作平面的函数,输入为平面的原点和法向量 2572 | internal SketchPlane CreateSketchPlane(Autodesk.Revit.DB.XYZ normal, Autodesk.Revit.DB.XYZ origin) 2573 | { 2574 | // 首先创建几何平面 2575 | Plane geometryPlane = m_revit.Create.NewPlane(normal, origin); 2576 | if (null == geometryPlane) 2577 | { 2578 | return null; 2579 | } 2580 | // 根绝几何平面创建工作平面 2581 | SketchPlane plane = SketchPlane.Create(m_familyDocument, geometryPlane); 2582 | if (null == plane) 2583 | { 2584 | return null; 2585 | } 2586 | return plane; 2587 | } 2588 | 2589 | // 创建用于拉伸的轮廓线 2590 | private CurveArrArray CreateExtrusionProfile() 2591 | { 2592 | // 轮廓线可以包括一个或者多个闭合的轮廓,所以最后返回是CurveArrArray 2593 | CurveArrArray curveArrArray = new CurveArrArray(); 2594 | CurveArray curveArray1 = new CurveArray(); 2595 | 2596 | // 创建一个正方体的轮廓线,先创建点,再创建线,最后组合成轮廓。 2597 | Autodesk.Revit.DB.XYZ p0 = Autodesk.Revit.DB.XYZ.Zero; 2598 | Autodesk.Revit.DB.XYZ p1 = new Autodesk.Revit.DB.XYZ(10, 0, 0); 2599 | Autodesk.Revit.DB.XYZ p2 = new Autodesk.Revit.DB.XYZ(10, 10, 0); 2600 | Autodesk.Revit.DB.XYZ p3 = new Autodesk.Revit.DB.XYZ(0, 10, 0); 2601 | Line line1 = Line.CreateBound(p0, p1); 2602 | Line line2 = Line.CreateBound(p1, p2); 2603 | Line line3 = Line.CreateBound(p2, p3); 2604 | Line line4 = Line.CreateBound(p3, p0); 2605 | curveArray1.Append(line1); 2606 | curveArray1.Append(line2); 2607 | curveArray1.Append(line3); 2608 | curveArray1.Append(line4); 2609 | curveArrArray.Append(curveArray1); 2610 | return curveArrArray; 2611 | } 2612 | 2613 | private void CreateExtrusion(FamilyItemFactory familyCreator) 2614 | { 2615 | // 调用函数创建拉伸的轮廓线和工作平面 2616 | CurveArrArray curveArrArray = CreateExtrusionProfile(); 2617 | SketchPlane sketchPlane = CreateSketchPlane(XYZ.BasisZ, XYZ.Zero); 2618 | 2619 | // 调用API创建拉伸(实心正方体) 2620 | Extrusion rectExtrusion = familyCreator.NewExtrusion(true, curveArrArray, sketchPlane, 10) 2621 | // 可能我们会希望把拉伸体移动到希望的位置上 2622 | XYZ transPoint1 = new XYZ(-16, 0, 0); 2623 | ElementTransformUtils.MoveElement(m_familyDocument, rectExtrusion.Id, transPoint1); 2624 | } 2625 | 2626 | //============代码片段7-14 创建融合体============ 2627 | private void CreateBlend(FamilyItemFactory familyCreator) 2628 | { 2629 | CurveArray topProfile = new CurveArray(); 2630 | CurveArray baseProfile = new CurveArray(); 2631 | 2632 | // 创建工作平面,CreateSketchPlane见上一个例子。 2633 | Autodesk.Revit.DB.XYZ normal = Autodesk.Revit.DB.XYZ.BasisZ; 2634 | SketchPlane sketchPlane = CreateSketchPlane(normal, Autodesk.Revit.DB.XYZ.Zero); 2635 | 2636 | // 创建底部的闭合二维轮廓 2637 | Autodesk.Revit.DB.XYZ p00 = Autodesk.Revit.DB.XYZ.Zero; 2638 | Autodesk.Revit.DB.XYZ p01 = new Autodesk.Revit.DB.XYZ(10, 0, 0); 2639 | Autodesk.Revit.DB.XYZ p02 = new Autodesk.Revit.DB.XYZ(10, 10, 0); 2640 | Autodesk.Revit.DB.XYZ p03 = new Autodesk.Revit.DB.XYZ(0, 10, 0); 2641 | Line line01 = Line.CreateBound(p00, p01); 2642 | Line line02 = Line.CreateBound(p01, p02); 2643 | Line line03 = Line.CreateBound(p02, p03); 2644 | Line line04 = Line.CreateBound(p03, p00); 2645 | baseProfile.Append(line01); 2646 | baseProfile.Append(line02); 2647 | baseProfile.Append(line03); 2648 | baseProfile.Append(line04); 2649 | 2650 | // 创建顶部的闭合二维轮廓 2651 | Autodesk.Revit.DB.XYZ p10 = new Autodesk.Revit.DB.XYZ(5, 2, 10); 2652 | Autodesk.Revit.DB.XYZ p11 = new Autodesk.Revit.DB.XYZ(8, 5, 10); 2653 | Autodesk.Revit.DB.XYZ p12 = new Autodesk.Revit.DB.XYZ(5, 8, 10); 2654 | Autodesk.Revit.DB.XYZ p13 = new Autodesk.Revit.DB.XYZ(2, 5, 10); 2655 | Line line11 = Line.CreateBound(p10, p11); 2656 | Line line12 = Line.CreateBound(p11, p12); 2657 | Line line13 = Line.CreateBound(p12, p13); 2658 | Line line14 = Line.CreateBound(p13, p10); 2659 | topProfile.Append(line11); 2660 | topProfile.Append(line12); 2661 | topProfile.Append(line13); 2662 | topProfile.Append(line14); 2663 | 2664 | // 利用底部和顶部的轮廓来创建融合 2665 | Blend blend = familyCreator.NewBlend(true, topProfile, baseProfile, sketchPlane); 2666 | } 2667 | 2668 | //============代码片段7-15 编辑融合体============ 2669 | public void AccessBlend(Blend blend) 2670 | { 2671 | // 得到融合体的底部和顶部轮廓线 2672 | CurveArrArray baseProfile = blend.BottomProfile; 2673 | CurveArrArray topProfile = blend.TopProfile; 2674 | 2675 | // 通过修改TopOffset属性来让融合体的顶部更高 2676 | blend.TopOffset = blend.TopOffset + 1; 2677 | 2678 | // 修改融合体顶部和底部的映射关系 2679 | VertexIndexPairArray currentMap = blend.GetVertexConnectionMap(); 2680 | VertexIndexPairArray newMap = new VertexIndexPairArray(); 2681 | List topIndexes = new List(); 2682 | List bottomIndexes = new List(); 2683 | foreach(VertexIndexPair pair in currentMap) 2684 | { 2685 | topIndexes.Add(pair.Top); 2686 | bottomIndexes.Add(pair.Bottom); 2687 | } 2688 | int lastTopindex = topIndexes.Last(); 2689 | topIndexes.RemoveAt(topIndexes.Count - 1); 2690 | topIndexes.Insert(0, lastTopindex); 2691 | for(int idx = 0; idx < bottomIndexes.Count; idx++) 2692 | { 2693 | newMap.Append(new VertexIndexPair(topIndexes[idx], bottomIndexes[idx])); 2694 | } 2695 | blend.SetVertexConnectionMap(newMap); 2696 | } 2697 | 2698 | //============代码片段7-16 创建旋转体============ 2699 | private void CreateRevolution(FamilyItemFactory familyCreator) 2700 | { 2701 | CurveArrArray curveArrArray = new CurveArrArray(); 2702 | CurveArray curveArray = new CurveArray(); 2703 | 2704 | // 创建工作平面,CreateSketchPlane参见Extrusion中的例子。 2705 | Autodesk.Revit.DB.XYZ normal = Autodesk.Revit.DB.XYZ.BasisZ; 2706 | SketchPlane sketchPlane = CreateSketchPlane(normal, Autodesk.Revit.DB.XYZ.Zero); 2707 | 2708 | // 创建一个正方体的轮廓线 2709 | Autodesk.Revit.DB.XYZ p0 = Autodesk.Revit.DB.XYZ.Zero; 2710 | Autodesk.Revit.DB.XYZ p1 = new Autodesk.Revit.DB.XYZ(10, 0, 0); 2711 | Autodesk.Revit.DB.XYZ p2 = new Autodesk.Revit.DB.XYZ(10, 10, 0); 2712 | Autodesk.Revit.DB.XYZ p3 = new Autodesk.Revit.DB.XYZ(0, 10, 0); 2713 | Line line1 = Line.CreateBound(p0, p1); 2714 | Line line2 = Line.CreateBound(p1, p2); 2715 | Line line3 = Line.CreateBound(p2, p3); 2716 | Line line4 = Line.CreateBound(p3, p0); 2717 | curveArray.Append(line1); 2718 | curveArray.Append(line2); 2719 | curveArray.Append(line3); 2720 | curveArray.Append(line4); 2721 | 2722 | // NewRevolution函数需要一个轮廓线的集合来满足复杂的轮廓线,比如“回”字形。 2723 | curveArrArray.Append(curveArray); 2724 | 2725 | // 创建旋转轴 2726 | Autodesk.Revit.DB.XYZ pp = new Autodesk.Revit.DB.XYZ(1, -1, 0); 2727 | Line axis1 = Line.CreateBound(Autodesk.Revit.DB.XYZ.Zero, pp); 2728 | 2729 | // 利用轮廓线和旋转轴来创建旋转体 2730 | Revolution revolution1 = familyCreator.NewRevolution(true, curveArrArray, sketchPlane, axis1, -Math.PI, 0); 2731 | } 2732 | 2733 | //============代码片段7-17 创建放样体============ 2734 | private void CreateSweep(Autodesk.Revit.Creation.Application appCreator, 2735 | FamilyItemFactory familyCreator) 2736 | { 2737 | CurveArrArray arrarr = new CurveArrArray(); 2738 | CurveArray arr = new CurveArray(); 2739 | 2740 | // 创建路径平面,CreateSketchPlane参见Extrusion中的例子。 2741 | Autodesk.Revit.DB.XYZ normal = Autodesk.Revit.DB.XYZ.BasisZ; 2742 | SketchPlane sketchPlane = CreateSketchPlane(normal, Autodesk.Revit.DB.XYZ.Zero); 2743 | 2744 | // 创建用于放样的轮廓,这里创建轮廓线再生成轮廓的方式 2745 | Autodesk.Revit.DB.XYZ pnt1 = new Autodesk.Revit.DB.XYZ(0, 0, 0); 2746 | Autodesk.Revit.DB.XYZ pnt2 = new Autodesk.Revit.DB.XYZ(2, 0, 0); 2747 | Autodesk.Revit.DB.XYZ pnt3 = new Autodesk.Revit.DB.XYZ(1, 1, 0); 2748 | arr.Append(Arc.Create(pnt2, 1.0d, 0.0d, 180.0d, Autodesk.Revit.DB.XYZ.BasisX, Autodesk.Revit.DB.XYZ.BasisY)); 2749 | arr.Append(Arc.Create(pnt1, pnt3, pnt2)); 2750 | arrarr.Append(arr); 2751 | SweepProfile profile = appCreator.NewCurveLoopsProfile(arrarr); 2752 | 2753 | // 创建用于放样的路径,该路径包括2条线段 2754 | Autodesk.Revit.DB.XYZ pnt4 = new Autodesk.Revit.DB.XYZ(10, 0, 0); 2755 | Autodesk.Revit.DB.XYZ pnt5 = new Autodesk.Revit.DB.XYZ(0, 10, 0); 2756 | Autodesk.Revit.DB.XYZ pnt6 = new Autodesk.Revit.DB.XYZ(5, 13, 0); 2757 | Curve curve = Line.CreateBound(pnt4, pnt5); 2758 | Curve curve1 = Line.CreateBound(pnt5, pnt6); 2759 | CurveArray curves = new CurveArray(); 2760 | curves.Append(curve); 2761 | curves.Append(curve1); 2762 | 2763 | // 利用轮廓和拉伸路径来创建放样,轮廓线位于拉伸路径的第二条线段的中心点 2764 | Sweep sweep1 = familyCreator.NewSweep(true, curves, sketchPlane, profile, 1, ProfilePlaneLocation.MidPoint); 2765 | } 2766 | 2767 | //============代码片段7-18 创建放样融合体============ 2768 | private void CreateSweepBlend(Autodesk.Revit.Creation.Application appCreator, 2769 | FamilyItemFactory familyCreator) 2770 | { 2771 | // 创建底部的轮廓线 2772 | Autodesk.Revit.DB.XYZ pnt1 = new Autodesk.Revit.DB.XYZ(0, 0, 0); 2773 | Autodesk.Revit.DB.XYZ pnt2 = new Autodesk.Revit.DB.XYZ(1, 0, 0); 2774 | Autodesk.Revit.DB.XYZ pnt3 = new Autodesk.Revit.DB.XYZ(1, 1, 0); 2775 | Autodesk.Revit.DB.XYZ pnt4 = new Autodesk.Revit.DB.XYZ(0, 1, 0); 2776 | Autodesk.Revit.DB.XYZ pnt5 = new Autodesk.Revit.DB.XYZ(0, 0, 1); 2777 | CurveArrArray arrarr1 = new CurveArrArray(); 2778 | CurveArray arr1 = new CurveArray(); 2779 | arr1.Append(Line.CreateBound(pnt1, pnt2)); 2780 | arr1.Append(Line.CreateBound(pnt2, pnt3)); 2781 | arr1.Append(Line.CreateBound(pnt3, pnt4)); 2782 | arr1.Append(Line.CreateBound(pnt4, pnt1)); 2783 | arrarr1.Append(arr1); 2784 | 2785 | // 创建顶部的轮廓线 2786 | Autodesk.Revit.DB.XYZ pnt6 = new Autodesk.Revit.DB.XYZ(0.5, 0, 0); 2787 | Autodesk.Revit.DB.XYZ pnt7 = new Autodesk.Revit.DB.XYZ(1, 0.5, 0); 2788 | Autodesk.Revit.DB.XYZ pnt8 = new Autodesk.Revit.DB.XYZ(0.5, 1, 0); 2789 | Autodesk.Revit.DB.XYZ pnt9 = new Autodesk.Revit.DB.XYZ(0, 0.5, 0); 2790 | CurveArrArray arrarr2 = new CurveArrArray(); 2791 | CurveArray arr2 = new CurveArray(); 2792 | arr2.Append(Line.CreateBound(pnt6, pnt7)); 2793 | arr2.Append(Line.CreateBound(pnt7, pnt8)); 2794 | arr2.Append(Line.CreateBound(pnt8, pnt9)); 2795 | arr2.Append(Line.CreateBound(pnt9, pnt6)); 2796 | arrarr2.Append(arr2); 2797 | 2798 | // 利用底部和顶部的轮廓线生成底部和顶部的轮廓。 2799 | SweepProfile bottomProfile = appCreator.NewCurveLoopsProfile(arrarr1); 2800 | SweepProfile topProfile = appCreator.NewCurveLoopsProfile(arrarr2); 2801 | 2802 | // 创建放样融合的拉伸路径 2803 | Autodesk.Revit.DB.XYZ pnt10 = new Autodesk.Revit.DB.XYZ(5, 0, 0); 2804 | Autodesk.Revit.DB.XYZ pnt11 = new Autodesk.Revit.DB.XYZ(0, 20, 0); 2805 | Curve curve = Line.CreateBound(pnt10, pnt11); 2806 | 2807 | // 创建路径平面,CreateSketchPlane参见Extrusion中的例子。 2808 | Autodesk.Revit.DB.XYZ normal = Autodesk.Revit.DB.XYZ.BasisZ; 2809 | SketchPlane sketchPlane = CreateSketchPlane(normal, Autodesk.Revit.DB.XYZ.Zero); 2810 | 2811 | // 利用底部和顶部的轮廓和拉伸路径创建放样融合 2812 | SweptBlend newSweptBlend1 = familyCreator.NewSweptBlend(true, curve, sketchPlane, bottomProfile, topProfile); 2813 | } 2814 | 2815 | //============代码片段7-19 管理图元可见性============ 2816 | public void AccessFamilyElementVisibility(Extrusion extrusion) 2817 | { 2818 | // 得到管理拉伸体的可见性的实例,并读取详细程度的设置 2819 | FamilyElementVisibility visibility = extrusion.GetVisibility(); 2820 | FamilyElementVisibilityType visibilityType = visibility.VisibilityType; 2821 | bool shownInCoarse = visibility.IsShownInCoarse; 2822 | bool shownInMedium = visibility.IsShownInMedium; 2823 | bool shownInFine = visibility.IsShownInFine; 2824 | 2825 | // 设置为在各种详细程度中都显示拉伸体 2826 | visibility.IsShownInCoarse = true; 2827 | visibility.IsShownInMedium = true; 2828 | visibility.IsShownInFine = true; 2829 | // 注意:必须把可见性的修改设置回拉伸体 2830 | extrusion.SetVisibility(visibility); 2831 | } 2832 | 2833 | //============代码片段8-1:获取视图类型============ 2834 | //Autodesk.Revit.DB.View view = GetView(); 2835 | //两种判断视图类型的方法: 2836 | //第一种: 2837 | ViewType viewType = view.ViewType; 2838 | switch (viewType) 2839 | { 2840 | case Autodesk.Revit.DB.ViewType.ThreeD: 2841 | // 视图类型是三维视图 2842 | break; 2843 | // 其他类型 2844 | } 2845 | 2846 | // 第二种: 2847 | if (view is View3D) 2848 | { 2849 | // view的类类型是三维视图 2850 | } 2851 | 2852 | //============代码片段8-2:获取视图中可见的元素============ 2853 | //找到视图中所有可见的元素 2854 | FilteredElementCollector elemCollector = new FilteredElementCollector(document, viewId); 2855 | foreach (Element elem in elemCollector) 2856 | { 2857 | //操作元素elem 2858 | } 2859 | 2860 | //============代码片段8-3:创建一个正交三维视图============ 2861 | private void CreateView3D(Autodesk.Revit.Document doc, ElementId viewTypeId) 2862 | { 2863 | try 2864 | { 2865 | // Create a new View3D 2866 | XYZ direction = new XYZ(1, 1, 1); 2867 | View3D view3D = View3D.CreateIsometric(doc, viewTypeId); 2868 | if (null == view3D) 2869 | return; 2870 | 2871 | // The created View3D isn't perspective. 2872 | Debug.Assert(false == view3D.IsPerspective); 2873 | } 2874 | catch (Exception e) 2875 | { 2876 | Debug.WriteLine(e.ToString()); 2877 | } 2878 | } 2879 | 2880 | //============代码片段8-4:显示剖面框============ 2881 | private void ShowHideSectionBox(View3D view3D) 2882 | { 2883 | view3D.IsSectionBoxActive = true; 2884 | } 2885 | 2886 | //============代码片段8-5:创建楼层平面和天花板平面============ 2887 | private void CreatePlanView(Autodesk.Revit.Document doc, ElementId viewTypeId) 2888 | { 2889 | try 2890 | { 2891 | using(Transaction tr = new Transaction(doc)) 2892 | { 2893 | tr.Start(“创建平面视图”); 2894 | double elevation = 10.0; 2895 | Level level1 = doc.Create.NewLevel(elevation); 2896 | ViewPlan floorView = ViewPlan.Create(doc, viewTypeId, level1.Id); 2897 | tr.Commit(); 2898 | } 2899 | } 2900 | catch (Exception exp) 2901 | { 2902 | MessageBox.Show(exp.ToString()); 2903 | } 2904 | } 2905 | 2906 | //============代码片段8-6:创建和打印一个图纸视图============ 2907 | private void CreateSheetView(Autodesk.Revit.Document doc) 2908 | { 2909 | // Get an available title block from document 2910 | FamilySymbolSet fsSet = doc.TitleBlocks; 2911 | if (fsSet.Size == 0) 2912 | { 2913 | MessageBox.Show("No title blocks"); 2914 | return; 2915 | } 2916 | 2917 | FamilySymbol fs = null; 2918 | foreach (FamilySymbol f in fsSet) 2919 | { 2920 | if (null != f) 2921 | { 2922 | fs = f; 2923 | break; 2924 | } 2925 | } 2926 | 2927 | try 2928 | { 2929 | // Create a sheet view 2930 | ViewSheet viewSheet = ViewSheet.Create(doc, fs); 2931 | if (null == viewSheet) 2932 | return; 2933 | 2934 | // Add current view onto the center of the sheet 2935 | UV location = new UV( 2936 | (viewSheet.Outline.Max.U - viewSheet.Outline.Min.U) / 2, 2937 | (viewSheet.Outline.Max.V - viewSheet.Outline.Min.V) / 2); 2938 | 2939 | XYZ point = new XYZ(UV.U, UV.V, 0); 2940 | Viewport.Create(doc, viewSheep.Id, doc.ActiveView.Id, point); 2941 | 2942 | // Print the sheet out 2943 | if (viewSheet.CanBePrinted) 2944 | { 2945 | if (MessageBox.Show("Print the sheet?", "Revit", 2946 | MessageBoxButtons.YesNo) == DialogResult.Yes) 2947 | viewSheet.Print(); 2948 | } 2949 | } 2950 | catch (Exception e) 2951 | { 2952 | MessageBox.Show(e.ToString()); 2953 | } 2954 | } 2955 | 2956 | //============代码片段9-1:DocumentOpened事件============ 2957 | public class Application_DocumentOpened : IExternalApplication 2958 | { 2959 | public IExternalApplication.Result OnStartup(ControlledApplication application) 2960 | { 2961 | try 2962 | { 2963 | //注册事件 2964 | application.DocumentOpened += new EventHandler 2965 | (application_DocumentOpened); 2966 | } 2967 | catch (Exception) 2968 | { 2969 | return Autodesk.Revit.UI.Result.Failed; 2970 | } 2971 | 2972 | return Autodesk.Revit.UI.Result.Succeeded; 2973 | } 2974 | 2975 | public IExternalApplication.Result OnShutdown(ControlledApplication application) 2976 | { 2977 | //注销事件 2978 | application.DocumentOpened -= new EventHandler 2979 | (application_DocumentOpened); 2980 | return Autodesk.Revit.UI.Result.Succeeded; 2981 | } 2982 | 2983 | 2984 | public void application_DocumentOpened(object sender, DocumentOpenedEventArgs args) 2985 | { 2986 | //从事件参数中获得文档对象 2987 | Document doc = args.Document; 2988 | 2989 | Transaction transaction = new Transaction(doc, "Edit Address"); 2990 | if (transaction.Start() == TransactionStatus.Started) 2991 | { 2992 | doc.ProjectInformation.Address = 2993 | "United States - Massachusetts - Waltham - 1560 Trapelo Road"; 2994 | transaction.Commit(); 2995 | } 2996 | } 2997 | } 2998 | 2999 | //============代码片段9-2:DocumentSavingAs事件响应函数============ 3000 | private void CheckProjectStatusInitial(Object sender, DocumentSavingAsEventArgs args) 3001 | { 3002 | Document doc = args.Document; 3003 | ProjectInfo proInfo = doc.ProjectInformation; 3004 | 3005 | // 项目信息只存在于项目文档中。 3006 | if (null != proInfo) 3007 | { 3008 | if (string.IsNullOrEmpty(proInfo.Status)) 3009 | { 3010 | 3011 | // 取消另存行为 3012 | args.Cancel = true; 3013 | MessageBox.Show("项目参数没有设置。取消保存。"); 3014 | } 3015 | } 3016 | } 3017 | 3018 | //============代码片段9-3:闲置事件响应函数============ 3019 | //实现外部程序的Execute函数 3020 | //创建一个文字,并且注册一个闲置事件 3021 | TextNote textNote = null; 3022 | String oldDateTime = null; 3023 | public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) 3024 | { 3025 | UIApplication uiApp = new UIApplication(commandData.Application.Application); 3026 | Document doc = commandData.Application.ActiveUIDocument.Document; 3027 | using (Transaction t = new Transaction(doc, "Text Note Creation")) 3028 | { 3029 | t.Start(); 3030 | textNote = doc.Create.NewTextNote(doc.ActiveView, XYZ.Zero, XYZ.BasisX, XYZ.BasisY, 0, TextAlignFlags.TEF_ALIGN_LEFT, DateTime.Now.ToString()); 3031 | t.Commit(); 3032 | } 3033 | oldDateTime = DateTime.Now.ToString(); 3034 | uiApp.Idling += new EventHandler(idleUpdate); 3035 | return Result.Succeeded; 3036 | } 3037 | 3038 | //闲置事件处理函数 3039 | //当时间有更新就将文字内容改为当前时间 3040 | public void idleUpdate(object sender, IdlingEventArgs e) 3041 | { 3042 | UIApplication uiApp = sender as UIApplication; 3043 | Document doc = uiApp.ActiveUIDocument.Document; 3044 | if (oldDateTime != DateTime.Now.ToString()) 3045 | { 3046 | using (Transaction transaction = new Transaction(doc, "Text Note Update")) 3047 | { 3048 | transaction.Start(); 3049 | textNote.Text = DateTime.Now.ToString(); 3050 | transaction.Commit(); 3051 | } 3052 | oldDateTime = DateTime.Now.ToString(); 3053 | } 3054 | } 3055 | 3056 | //============代码片段9-4:实现IExternalEventHandler接口============ 3057 | public class ExternalEventExample : IExternalEventHandler 3058 | { 3059 | public void Execute(UIApplication app) 3060 | { 3061 | TaskDialog.Show("External Event", "Click Close to close."); 3062 | } 3063 | public string GetName() 3064 | { 3065 | return "External Event Example"; 3066 | } 3067 | } 3068 | 3069 | //============代码片段9-5:外部事件的注册和触发============ 3070 | public class ExternalEventExampleApp : IExternalApplication 3071 | { 3072 | public static ExternalEventExampleApp thisApp = null; 3073 | // 非模态对话框实例 3074 | private ExternalEventExampleDialog m_MyForm; 3075 | 3076 | public Result OnShutdown(UIControlledApplication application) 3077 | { 3078 | if (m_MyForm != null && m_MyForm.Visible) 3079 | { 3080 | m_MyForm.Close(); 3081 | } 3082 | 3083 | return Result.Succeeded; 3084 | } 3085 | 3086 | public Result OnStartup(UIControlledApplication application) 3087 | { 3088 | m_MyForm = null; // 在外部命令中创建非模态对话框 3089 | thisApp = this; // 静态变量,保存Application实例 3090 | 3091 | return Result.Succeeded; 3092 | } 3093 | 3094 | // 外部命令调用此方法 3095 | public void ShowForm(UIApplication uiapp) 3096 | { 3097 | // 如果没有创建对话框,创建并显示它 3098 | if (m_MyForm == null || m_MyForm.IsDisposed) 3099 | { 3100 | // 新建一个外部事件响应实例 3101 | ExternalEventExample handler = new ExternalEventExample(); 3102 | 3103 | // 新建一个外部事件实例 3104 | ExternalEvent exEvent = ExternalEvent.Create(handler); 3105 | 3106 | // 把上面两个实例传给对话框. 3107 | m_MyForm = new ExternalEventExampleDialog(exEvent, handler); 3108 | m_MyForm.Show(); 3109 | } 3110 | } 3111 | } 3112 | 3113 | [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)] 3114 | [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)] 3115 | public class Command : IExternalCommand 3116 | { 3117 | public virtual Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) 3118 | { 3119 | try 3120 | { 3121 | ExternalEventExampleApp.thisApp.ShowForm(commandData.Application); 3122 | return Result.Succeeded; 3123 | } 3124 | catch (Exception ex) 3125 | { 3126 | message = ex.Message; 3127 | return Result.Failed; 3128 | } 3129 | } 3130 | } 3131 | 3132 | public partial class ExternalEventExampleDialog : Form 3133 | { 3134 | private ExternalEvent m_ExEvent; 3135 | private ExternalEventExample m_Handler; 3136 | 3137 | public ExternalEventExampleDialog(ExternalEvent exEvent, ExternalEventExample handler) 3138 | { 3139 | InitializeComponent(); 3140 | m_ExEvent = exEvent; 3141 | m_Handler = handler; 3142 | } 3143 | 3144 | protected override void OnFormClosed(FormClosedEventArgs e) 3145 | { 3146 | // 保存的实例需要释放 3147 | m_ExEvent.Dispose(); 3148 | m_ExEvent = null; 3149 | m_Handler = null; 3150 | 3151 | base.OnFormClosed(e); 3152 | } 3153 | 3154 | private void closeButton_Click(object sender, EventArgs e) 3155 | { 3156 | Close(); 3157 | } 3158 | //按钮响应函数,点击按钮触发外部事件 3159 | private void showMessageButton_Click(object sender, EventArgs e) 3160 | { 3161 | m_ExEvent.Raise(); 3162 | } 3163 | } 3164 | 3165 | //============代码片段10-1:创建一个文本框============ 3166 | // 继承IExternalApplication接口 3167 | public class Ribbon : Autodesk.Revit.DB.IExternalDBApplication 3168 | { 3169 | /// 实现OnStartup 3170 | public Autodesk.Revit.UI.Result OnStartup(UIControlledApplication application) 3171 | { 3172 | // 在OnStartup函数里创建一个Ribbon文本框 3173 | application.CreateRibbonTab("CustomTag"); 3174 | RibbonPanel panel = application.CreateRibbonPanel("CustomTag", "CustomPanel"); 3175 | TextBox textBox = panel.AddItem(new TextBoxData("CustomTextBox")) as TextBox; 3176 | 3177 | return Autodesk.Revit.UI.Result.Succeeded; 3178 | } 3179 | // 实现OnStartup 3180 | public Autodesk.Revit.UI.Result OnShutdown(UIControlledApplication application) 3181 | { 3182 | return Autodesk.Revit.UI.Result.Succeeded; 3183 | } 3184 | } 3185 | 3186 | //============代码片段10-2:创建一个命令按钮============ 3187 | PushButtonData pushButtonData = new PushButtonData("name", "Text", ECAssemblyPath, ECFullName); 3188 | PushButton pushButton = panel.AddItem(pushButtonData) as PushButton; 3189 | 3190 | //============代码片段10-3:创建一个包含两个子命令按钮的下拉切换按钮============ 3191 | #region 创建一个包含两个 pushButton 的 SplitButton,用来 创建结构墙和非结构墙 3192 | // 创建一个SplitButton 3193 | SplitButtonData splitButtonData = new SplitButtonData("NewWallSplit", "Create Wall"); 3194 | SplitButton splitButton = panel.AddItem(splitButtonData) as SplitButton; 3195 | 3196 | // 创建一个pushButton加到SplitButton的下拉列表里 3197 | PushButton pushButton = splitButton.AddPushButton(new PushButtonData("WallPush", "Wall", 3198 | AddInFullPath, "Revit.SDK.Samples.Ribbon.CS.CreateWall")); 3199 | pushButton.LargeImage = new BitmapImage(new Uri(Path.Combine(ButtonIconsFolder, "CreateWall.png"), UriKind.Absolute)); 3200 | pushButton.Image = new BitmapImage(new Uri(Path.Combine(ButtonIconsFolder, "CreateWall-S.png"), UriKind.Absolute)); 3201 | pushButton.ToolTip = "Creates a partition wall in the building model."; 3202 | pushButton.ToolTipImage = new BitmapImage(new Uri(Path.Combine(ButtonIconsFolder, "CreateWallTooltip.bmp"), UriKind.Absolute)); 3203 | 3204 | // 创建另一个pushButton加到SplitButton的下拉列表里 3205 | pushButton = splitButton.AddPushButton(new PushButtonData("StrWallPush", "Structure Wall", 3206 | AddInPath, "Revit.SDK.Samples.Ribbon.CS.CreateStructureWall")); 3207 | pushButton.LargeImage = new BitmapImage(new Uri(Path.Combine(ButtonIconsFolder, "StrcturalWall.png"), UriKind.Absolute)); 3208 | pushButton.Image = new BitmapImage(new Uri(Path.Combine(ButtonIconsFolder, "StrcturalWall-S.png"), UriKind.Absolute)); 3209 | #endregion 3210 | 3211 | //============代码片段10-4:创建一个下拉组合框来选择墙的类型============ 3212 | // Prepare data to create ComboBox 3213 | ComboBoxData comboBoxData = new ComboBoxData("WallShapeComboBox"); 3214 | // Create ComboBox 3215 | ComboBox comboboxWallShape = panel.AddItem(comboBoxData) as ComboBox; 3216 | 3217 | // Add options to WallShapeComboBox 3218 | // Prepare data to create ComboBoxMember 3219 | ComboBoxMemberData boxMemberData = new ComboBoxMemberData("RectangleWall","RectangleWall"); 3220 | // Create ComboBoxMember 3221 | ComboBoxMember boxMember = comboboxWallShape.AddItem(boxMemberData); 3222 | boxMember.Image = new BitmapImage(new Uri(Path.Combine(ButtonIconsFolder, "RectangleWall.png"), UriKind.Absolute)); 3223 | 3224 | // Prepare data to create ComboBoxMember 3225 | boxMemberData = new ComboBoxMemberData("CircleWall", "CircleWall"); 3226 | // Create ComboBoxMember 3227 | boxMember = comboboxWallShape.AddItem(boxMemberData); 3228 | boxMember.Image = new BitmapImage(new Uri(Path.Combine(ButtonIconsFolder, "CircleWall.png"), UriKind.Absolute)); 3229 | 3230 | // Prepare data to create ComboBoxMember 3231 | boxMemberData = new ComboBoxMemberData("TriangleWall", "TriangleWall"); 3232 | // Create ComboBoxMember 3233 | boxMember = comboboxWallShape.AddItem(boxMemberData); 3234 | boxMember.Image = new BitmapImage(new Uri(Path.Combine(ButtonIconsFolder, "TriangleWall.png"), UriKind.Absolute)); 3235 | 3236 | // Prepare data to create ComboBoxMember 3237 | boxMemberData = new ComboBoxMemberData("SquareWall", "SquareWall"); 3238 | // Create ComboBoxMember 3239 | boxMember = comboboxWallShape.AddItem(boxMemberData); 3240 | boxMember.Image = new BitmapImage(new Uri(Path.Combine(ButtonIconsFolder, "SquareWall.png"), UriKind.Absolute)); 3241 | 3242 | //============代码片段10-5:创建一个包含两个切换按钮的切换按钮组,其中每一个切换按钮都不执行具体的ExternalCommand,仅作为选择控件使用 ============ 3243 | // 创建一个RadioButtonGroup 3244 | RadioButtonGroupData radioButtonGroupData = new RadioButtonGroupData("WallTypeSelector"); 3245 | RadioButtonGroup radioButtonGroup = (RadioButtonGroup)( 3246 | panel.AddItem(radioButtonGroupData)); 3247 | 3248 | // 给RadioButtonGroup添加toggleButton 3249 | ToggleButton toggleButton = radioButtonGroup.AddItem( 3250 | new ToggleButtonData("Generic8", "Generic - 8\"")); 3251 | toggleButton.LargeImage = new BitmapImage(new Uri(Path.Combine(ButtonIconsFolder, 3252 | "Generic8.png"), UriKind.Absolute)); 3253 | toggleButton.Image = new BitmapImage(new Uri(Path.Combine(ButtonIconsFolder, 3254 | "Generic8-S.png"), UriKind.Absolute)); 3255 | 3256 | // 给RadioButtonGroup添加toggleButton 3257 | toggleButton = radioButtonGroup.AddItem( 3258 | new ToggleButtonData("ExteriorBrick", "Exterior - Brick")); 3259 | toggleButton.LargeImage = new BitmapImage(new Uri(Path.Combine(ButtonIconsFolder, 3260 | "ExteriorBrick.png"), UriKind.Absolute)); 3261 | toggleButton.Image = new BitmapImage(new Uri(Path.Combine(ButtonIconsFolder, 3262 | "ExteriorBrick-S.png"), UriKind.Absolute)); 3263 | 3264 | //============代码片段10-6:创建一个包含两个切换按钮的切换按钮组,其中每一个切换按钮都会执行具体的ExternalCommand============ 3265 | // 创建一个RadioButtonGroup 3266 | RadioButtonGroupData radioButtonGroupData = new RadioButtonGroupData("WallTypeSelector"); 3267 | RadioButtonGroup radioButtonGroup = (RadioButtonGroup)( 3268 | panel.AddItem(radioButtonGroupData)); 3269 | 3270 | // 给RadioButtonGroup添加toggleButton 3271 | ToggleButton toggleButton = radioButtonGroup.AddItem(new ToggleButtonData("Generic8", 3272 | "Generic - 8\"", 3273 | AddInPath, "Revit.SDK.Samples.Ribbon.CS.CreateGeneric8Wall")); 3274 | toggleButton.LargeImage = new BitmapImage(new Uri(Path.Combine(ButtonIconsFolder, 3275 | "Generic8.png"), UriKind.Absolute)); 3276 | toggleButton.Image = new BitmapImage(new Uri(Path.Combine(ButtonIconsFolder, 3277 | "Generic8-S.png"), UriKind.Absolute)); 3278 | 3279 | // 给RadioButtonGroup添加toggleButton 3280 | toggleButton = radioButtonGroup.AddItem(new ToggleButtonData("ExteriorBrick", 3281 | "Exterior - Brick", 3282 | AddInPath, "Revit.SDK.Samples.Ribbon.CS.CreateExteriorBrickWall ")); 3283 | toggleButton.LargeImage = new BitmapImage(new Uri(Path.Combine(ButtonIconsFolder, 3284 | "ExteriorBrick.png"), UriKind.Absolute)); 3285 | toggleButton.Image = new BitmapImage(new Uri(Path.Combine(ButtonIconsFolder, 3286 | "ExteriorBrick-S.png"), UriKind.Absolute)); 3287 | 3288 | //============代码片段10-7:EnterPresseds事件 handler============ 3289 | void SetTextValue(object sender, TextBoxEnterPressedEventArgs args) 3290 | { 3291 | string strText = m_textBox.Value as string; 3292 | } 3293 | 3294 | //============代码片段10-8:外部命令中Excute函数的定义============ 3295 | public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, 3296 | ref string message, Autodesk.Revit.DB.ElementSet elements) 3297 | { 3298 | Application app = commandData.Application.Application; 3299 | Document activeDoc = commandData.Application.ActiveUIDocument.Document; 3300 | 3301 | // 通过构造函数创建一个Revit任务对话框 3302 | TaskDialog mainDialog = new TaskDialog("自定义标题"); 3303 | mainDialog.MainInstruction = "任务对话框使用说明:"; 3304 | mainDialog.MainContent = 3305 | "这个例子演示如何通过Revit API自定义Revit样式任务对话框。"; 3306 | mainDialog.ExpandedContent = "在Revit中,任务对话框可以用于显示信息和接受简单输入。"; 3307 | 3308 | // 为任务对话框添加命令链接 3309 | mainDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, 3310 | "查看Revit Application信息"); 3311 | mainDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, 3312 | "查看当前文档信息"); 3313 | 3314 | // 设置普通按钮以及默认按钮 3315 | mainDialog.CommonButtons = TaskDialogCommonButtons.Ok | TaskDialogCommonButtons.Cancel; 3316 | mainDialog.DefaultButton = TaskDialogResult.Ok; 3317 | 3318 | mainDialog.VerificationText = "不再提示该消息"; 3319 | // 设置文字信息,一般为一个链接 3320 | mainDialog.FooterText = 3321 | "" 3322 | + "点击此处了解更多"; 3323 | 3324 | // 显示任务对话框,并取得返回值。 3325 | TaskDialogResult tResult = mainDialog.Show(); 3326 | 3327 | // 使用对话框返回值来做进一步的事情 3328 | if (TaskDialogResult.CommandLink1 == tResult) 3329 | { 3330 | TaskDialog dialog_CommandLink1 = new TaskDialog("版本信息"); 3331 | dialog_CommandLink1.MainInstruction = 3332 | "版本名: " + app.VersionName + "\n" 3333 | + "版本号: " + app.VersionNumber; 3334 | 3335 | dialog_CommandLink1.Show(); 3336 | 3337 | } 3338 | 3339 | else if (TaskDialogResult.CommandLink2 == tResult) 3340 | { 3341 | // 使用静态方法创建显示任务对话框 3342 | TaskDialog.Show("活动文档信息", 3343 | "活动文档标题: " + activeDoc.Title + "\n" 3344 | + "活动文档名: " + activeDoc.ActiveView.Name); 3345 | } 3346 | 3347 | return Autodesk.Revit.UI.Result.Succeeded; 3348 | } 3349 | 3350 | //============代码片段11-1:通过StructuralType区分结构柱,结构梁,结构支撑和独立基础============ 3351 | public void GetStructuralType(FamilyInstance familyInstance) 3352 | { 3353 | string message = ""; 3354 | switch (familyInstance.StructuralType) 3355 | { 3356 | case StructuralType.Beam: // 结构梁 3357 | message = "FamilyInstance is a beam."; 3358 | break; 3359 | case StructuralType.Brace: // 结构支撑 3360 | message = "FamilyInstance is a brace."; 3361 | break; 3362 | case StructuralType.Column: // 结构柱 3363 | message = "FamilyInstance is a column."; 3364 | break; 3365 | case StructuralType.Footing: // 独立地基 3366 | message = "FamilyInstance is a footing."; 3367 | break; 3368 | default: 3369 | message = "FamilyInstance is non-structural or unknown framing."; 3370 | break; 3371 | } 3372 | } 3373 | 3374 | //============代码片段11-2:获取边界条件的类别与几何信息============ 3375 | //BoundaryConditions BC 3376 | // 通过BOUNDARY_CONDITIONS_TYPE参数获取此边界条件的类别 3377 | Parameter param = BC.get_Parameter(BuiltInParameter.BOUNDARY_CONDITIONS_TYPE); 3378 | switch (param.AsInteger()) 3379 | { 3380 | case 0: // 点边界条件,几何信息表现为一个点 3381 | XYZ point = BC.Point; 3382 | break; 3383 | case 1: // 线边界条件,几何信息表现为一条线 3384 | Curve curve = BC.get_Curve(0); 3385 | break; 3386 | case 2: // 面边界条件,几何信息表现多条线的集合 3387 | CurveArray profile = new CurveArray(); 3388 | for (int i = 0; i < BC.NumCurves; i++) 3389 | { 3390 | profile.Append(BC.get_Curve(i)); 3391 | } 3392 | break; 3393 | default: 3394 | break; 3395 | } 3396 | 3397 | //============代码片段11-3:在结构柱上创建线边界条件============ 3398 | //FamilyInstance beam 3399 | //Autodesk.Revit.Creation.Document creDocument 3400 | AnalyticalModel beamAM = beam.GetAnalyticalModel(); 3401 | Curve curve = beamAM.GetCurve(); 3402 | AnalyticalModelSelector selector = new AnalyticalModelSelector(curve); 3403 | selector.CurveSelector = AnalyticalCurveSelector.WholeCurve; 3404 | Reference wholeCurveRef = beamAM.GetReference(selector); 3405 | 3406 | // 通过 NewLineBoundaryConditions 重载方法一创建线边界条件 3407 | BoundaryConditions createdBC1 = creDocument.NewLineBoundaryConditions(beamAM, 3408 | TranslationRotationValue.Release, 0, 3409 | TranslationRotationValue.Fixed, 0, 3410 | TranslationRotationValue.Fixed, 0, 3411 | TranslationRotationValue.Fixed, 0); 3412 | // 通过 NewLineBoundaryConditions 重载方法二创建线边界条件 3413 | BoundaryConditions createdBC2 = creDocument.NewLineBoundaryConditions(wholeCurveRef, 3414 | TranslationRotationValue.Release, 0, 3415 | TranslationRotationValue.Fixed, 0, 3416 | TranslationRotationValue.Fixed, 0, 3417 | TranslationRotationValue.Fixed, 0); 3418 | 3419 | //============代码片段11-4:获取分析模型============ 3420 | CurveArray profile = new CurveArray(); 3421 | // API 创建一个结构楼板 3422 | Floor struFloor = RevitDoc.Create.NewFloor(profile, true); 3423 | // Regenerate revit document 3424 | RevitDoc.Regenerate(); 3425 | // 获取改楼板的分析模型 3426 | AnalyticalModel floorAM = struFloor.GetAnalyticalModel(); 3427 | 3428 | //============代码片段11-5:获取独立基础的分析模型几何信息============ 3429 | // 该元素是独立基地 3430 | FamilyInstance familyInst = element as FamilyInstance; 3431 | if (null != familyInst && familyInst.StructuralType == StructuralType.Footing) 3432 | { 3433 | AnalyticalModel model = familyInst.GetAnalyticalModel(); 3434 | // 独立地基的分析模型被表达为一个点 3435 | if (model.IsSinglePoint() == true) 3436 | { 3437 | XYZ analyticalLocationPoint = model.GetPoint(); 3438 | } 3439 | } 3440 | 3441 | //============代码片段11-6:获取结构柱的分析模型几何信息============ 3442 | // 该元素为结构柱 3443 | FamilyInstance familyInst = element as FamilyInstance; 3444 | if (null != familyInst && familyInst.StructuralType == StructuralType.Column) 3445 | { 3446 | AnalyticalModel model = familyInst.GetAnalyticalModel(); 3447 | // 结构柱的分析结构被表达为一条线 3448 | if (model.IsSingleCurve() == true) 3449 | { 3450 | XYZ analyticalLocationPoint = model.GetCurve (); 3451 | } 3452 | } 3453 | 3454 | //============代码片段11-7:获取结构墙的分析模型几何信息============ 3455 | Wall wall = null; 3456 | // 获取结构墙的分析模型 3457 | AnalyticalModel amWall = wall.GetAnalyticalModel() as AnalyticalModel; 3458 | if (null == amWall) 3459 | { 3460 | // 建筑墙没有分析模型 3461 | return; 3462 | } 3463 | // 获取分析模型曲线 3464 | int modelCurveNum = amWall.GetCurves(AnalyticalCurveType.ActiveCurves).Count; 3465 | 3466 | //============代码片段11-8:获取独立基础的分析模型点的参照============ 3467 | // element: 一个独立基础 3468 | // 获取独立基础的分析模型 3469 | AnalyticalModel am = element.GetAnalyticalModel(); 3470 | AnalyticalModelSelector amSelector = new AnalyticalModelSelector(); 3471 | // 获取独立基础的分析模型点的几何引用 3472 | Reference refer = am.GetReference(amSelector); 3473 | 3474 | //============代码片段11-9:获取结构梁的分析模型曲线的几何引用============ 3475 | //element: 一个结构梁 3476 | // 获取结构梁的分析模型 3477 | AnalyticalModel am = element.GetAnalyticalModel(); 3478 | 3479 | // 获取结构梁的分析模型曲线的几何引用 3480 | AnalyticalModelSelector amSelector = new AnalyticalModelSelector(AnalyticalCurveSelector.WholeCurve); 3481 | Reference wholeCurveRefer = am.GetReference(amSelector); 3482 | 3483 | // 获取结构梁的分析模型曲线的起点的几何引用 3484 | amSelector = new AnalyticalModelSelector(AnalyticalCurveSelector.StartPoint); 3485 | Reference curveStartPointRefer = am.GetReference(amSelector); 3486 | 3487 | // 获取结构梁的分析模型曲线的终点的几何引用 3488 | amSelector = new AnalyticalModelSelector(AnalyticalCurveSelector.EndPoint); 3489 | Reference curveEndPointRefer = am.GetReference(amSelector); 3490 | 3491 | //============代码片段11-10:获取结构墙的分析模型曲线的参照============ 3492 | //element: 一个结构墙 3493 | // 获取结构墙的分析模型 3494 | AnalyticalModel am = element.GetAnalyticalModel(); 3495 | // 获取结构墙分析模型的曲线列表 3496 | IList amCurveList = am.GetCurves(AnalyticalCurveType.ActiveCurves); 3497 | 3498 | for (int curveIndex = 0; curveIndex < amCurveList.Count; curveIndex++) 3499 | { 3500 | // 获取结构墙的指定的分析模型曲线的几何引用 3501 | AnalyticalModelSelector amSelector = new AnalyticalModelSelector(amCurveList[curveIndex], AnalyticalCurveSelector.WholeCurve); 3502 | Reference wholeCurveRefer = am.GetReference(amSelector); 3503 | 3504 | // 获取结构墙的指定的分析模型曲线的起点的几何引用 3505 | amSelector = new AnalyticalModelSelector(amCurveList[curveIndex], AnalyticalCurveSelector.StartPoint); 3506 | Reference curveStartPointRefer = am.GetReference(amSelector); 3507 | 3508 | // 获取结构墙的指定的分析模型曲线的终点的几何引用 3509 | amSelector = new AnalyticalModelSelector(amCurveList[curveIndex], AnalyticalCurveSelector.EndPoint); 3510 | Reference curveEndPointRefer = am.GetReference(amSelector); 3511 | } 3512 | 3513 | //============代码片段11-11:设置结构柱分析模型底部Z方向投影为 柱底部============ 3514 | am.SetAlignmentMethod(AnalyticalElementSelector.StartOrBase, AnalyticalDirection.Z, AnalyticalAlignmentMethod.Projection); 3515 | am.SetAnalyticalProjectionType(AnalyticalElementSelector.StartOrBase, AnalyticalDirection.Z, AnalyticalProjectionType.Bottom); 3516 | 3517 | //============代码片段11-12:设置结构柱分析模型底部Z方向投影为 标高 1============ 3518 | am.SetAlignmentMethod(AnalyticalElementSelector.StartOrBase, AnalyticalDirection.Z, AnalyticalAlignmentMethod.Projection); 3519 | am.SetAnalyticalProjectionDatumPlane(AnalyticalElementSelector.StartOrBase, AnalyticalDirection.Z, level1Id); 3520 | 3521 | //============代码片段11-13:设置结构梁分析模型的近似曲线============ 3522 | if (am.CanApproximate()) 3523 | { 3524 | am.Approximate(true); 3525 | am.SetApproximationDeviation(1.5); 3526 | am.SetUsesHardPoints(false); 3527 | } 3528 | 3529 | //============代码片段11-14:设置分析模型的 分析为============ 3530 | if(am.IsAnalyzeAsValid(AnalyzeAs.Gravity)) 3531 | { 3532 | am.SetAnalyzeAs(AnalyzeAs.Gravity); 3533 | } 3534 | 3535 | //============代码片段11-15:楼板的支撑信息============ 3536 | public void GetSupportInfo_Floor(Floor floor) 3537 | { 3538 | // floor : 楼板 3539 | // 获取楼板的分析模型 3540 | AnalyticalModel amFloor = floor.GetAnalyticalModel(); 3541 | // 在这里IsElementFullySupported方法将返回true,这表明楼板被完全支撑 3542 | bool fullySuported = amFloor.IsElementFullySupported(); 3543 | 3544 | // 获取具体的支撑信息,将返回含有三个support成员的列表。每一个support都对应一根结构梁对地板提供的支撑 3545 | IList supportList = amFloor.GetAnalyticalModelSupports(); 3546 | foreach (AnalyticalModelSupport support in supportList) 3547 | { 3548 | // 返回当前提供支撑的分析梁的id 3549 | ElementId id = support.GetSupportingElement(); 3550 | // 返回CurveSupport,表明该支撑是一个线性支撑 3551 | AnalyticalSupportType supportType = support.GetSupportType(); 3552 | 3553 | // 根据支撑力类型的不同,可以分别通过GetPoint,GetCurve,GetFace这三种方法之一获取支撑力的具体几何位置 3554 | switch (supportType) 3555 | { 3556 | case AnalyticalSupportType.PointSupport: 3557 | XYZ point = support.GetPoint(); 3558 | break; 3559 | case AnalyticalSupportType.CurveSupport: 3560 | Curve curve = support.GetCurve(); 3561 | break; 3562 | case AnalyticalSupportType.SurfaceSupport: 3563 | Face face = support.GetFace(); 3564 | break; 3565 | case AnalyticalSupportType.UnknownSupport: 3566 | break; 3567 | } 3568 | 3569 | // 通过GetPriority方法可以获取当前支撑力的优先权。当一个物体被多项支撑时,该属性可对提供的支撑进行排序,从而可选取最优的支撑 3570 | AnalyticalSupportPriority supportPriority = support.GetPriority(); 3571 | } 3572 | } 3573 | 3574 | //============代码片段11-16:楼板的支撑信息============ 3575 | // 楼板的支撑信息 3576 | public void GetSupportInfo_Floor(Floor floor) 3577 | { 3578 | // floor : 楼板 3579 | // 获取楼板的分析模型 3580 | AnalyticalModel amFloor = floor.GetAnalyticalModel(); 3581 | // 在这里IsElementFullySupported方法将返回false,这表明楼板未被完全支撑 3582 | bool fullySuported = amFloor.IsElementFullySupported(); 3583 | 3584 | // 获取具体的支撑信息,将返回一个空列表。表示该楼板没有任何支撑物 3585 | IList supportList = amFloor.GetAnalyticalModelSupports(); 3586 | If(supportList.Count == 0) string message = “楼板没有支撑”; 3587 | } 3588 | 3589 | //============代码片段11-17:墙的支撑信息============ 3590 | // 该实例中墙的支撑信息 3591 | public void GetSupportInfo_Walls(Wall wall) 3592 | { 3593 | // wall : 四面墙中的任何一面墙 3594 | // 获取墙的分析模型 3595 | AnalyticalModel amWall = wall.GetAnalyticalModel(); 3596 | // 在这里IsElementFullySupported方法将返回true,这表明墙被完全支撑 3597 | bool fullySuported = amWall.IsElementFullySupported(); 3598 | 3599 | // 获取具体的支撑信息,这里返回只含有一个support成员的列表。这个support对应墙下面的楼板 3600 | IList supportList = amWall.GetAnalyticalModelSupports(); 3601 | foreach (AnalyticalModelSupport support in supportList) 3602 | { 3603 | // 返回当前提供支撑的楼板的分析模型的id 3604 | ElementId id = support.GetSupportingElement(); 3605 | // 返回CurveSupport,表明该支撑是一个线性支撑 3606 | AnalyticalSupportType supportType = support.GetSupportType(); 3607 | 3608 | // 根据支撑力类型的不同,可以分别通过GetPoint,GetCurve,GetFace这三种方法之一获取支撑力的具体几何位置 3609 | switch (supportType) 3610 | { 3611 | case AnalyticalSupportType.PointSupport: 3612 | XYZ point = support.GetPoint(); 3613 | break; 3614 | case AnalyticalSupportType.CurveSupport: 3615 | Curve curve = support.GetCurve(); 3616 | break; 3617 | case AnalyticalSupportType.SurfaceSupport: 3618 | Face face = support.GetFace(); 3619 | break; 3620 | case AnalyticalSupportType.UnknownSupport: 3621 | break; 3622 | } 3623 | 3624 | AnalyticalSupportPriority supportPriority = support.GetPriority(); 3625 | } 3626 | } 3627 | 3628 | //============代码片段11-18:结构梁的支撑信息============ 3629 | // 该实例中梁的支撑信息 3630 | public void GetSupportInfo_Beam(FamilyInstance beam) 3631 | { 3632 | // beam: 结构梁 3633 | // 获取梁的分析模型 3634 | AnalyticalModel amBeam = beam.GetAnalyticalModel(); 3635 | // 在这里IsElementFullySupported方法将返回false,这表明梁未被完全支撑 3636 | bool fullySuported = amBeam.IsElementFullySupported(); 3637 | 3638 | // 获取具体的支撑信息,这里返回只含有一个support成员的列表。这个support对应该示例中的结构柱 3639 | IList supportList = amBeam.GetAnalyticalModelSupports(); 3640 | foreach (AnalyticalModelSupport support in supportList) 3641 | { 3642 | // 返回提供该支撑的结构柱的分析模型的id 3643 | ElementId id = support.GetSupportingElement(); 3644 | // 返回PointSupport,表明该支撑是一个点支撑 3645 | AnalyticalSupportType supportType = support.GetSupportType(); 3646 | 3647 | // 根据支撑力类型的不同,可以分别通过GetPoint,GetCurve,GetFace这三种方法之一获取支撑力的具体几何位置 3648 | switch (supportType) 3649 | { 3650 | case AnalyticalSupportType.PointSupport: 3651 | XYZ point = support.GetPoint(); 3652 | break; 3653 | case AnalyticalSupportType.CurveSupport: 3654 | Curve curve = support.GetCurve(); 3655 | break; 3656 | case AnalyticalSupportType.SurfaceSupport: 3657 | Face face = support.GetFace(); 3658 | break; 3659 | case AnalyticalSupportType.UnknownSupport: 3660 | break; 3661 | } 3662 | 3663 | AnalyticalSupportPriority supportPriority = support.GetPriority(); 3664 | } 3665 | } 3666 | 3667 | //============代码片段11-19:调整结构柱分析模型的顶端向上(Z方向)偏移5============ 3668 | // columnAnalytical 结构柱的分析模型 3669 | AnalyticalElementSelector elemSelector = AnalyticalElementSelector.EndOrTop; 3670 | XYZ offset = new XYZ(0, 0, 5); 3671 | columnAnalytical.SetOffset(elemSelector, offset); 3672 | 3673 | // 返回 XYZ(0, 0, 5); 3674 | XYZ regetOffset = columnAnalytical.GetOffset(elemSelector); 3675 | 3676 | //============代码片段11-20:通过手动调整使结构柱的分析模型与某结构梁的分析模型相连接============ 3677 | // columnAnalytical:分析柱 3678 | // beamAnalytical 分析梁 3679 | // 判断该分析模型支持手动调整 3680 | if(columnAnalytical.SupportsManualAdjustment()) 3681 | { 3682 | Reference sourceRef = columnAnalytical.GetReference(new AnalyticalModelSelector(AnalyticalCurveSelector.EndPoint)); 3683 | Reference targetRef = beamAnalytical.GetReference(new AnalyticalModelSelector(AnalyticalCurveSelector.EndPoint)); 3684 | // 手动调整分析柱的终点到分析梁的终点 3685 | columnAnalytical.ManuallyAdjust(sourceRef, targetRef); 3686 | bool isManuallyAdjusted = columnAnalytical.IsManuallyAdjusted());//true 3687 | 3688 | // 将分析模型设置回默认位置 3689 | columnAnalytical.ResetManualAdjustment(); 3690 | isManuallyAdjusted = columnAnalytical.IsManuallyAdjusted()); //true 3691 | } 3692 | 3693 | //============代码片段11-21:读取Revit文档对象里所有的分析链接,包括自动创建的和手动创建的============ 3694 | public void ReadAnalyticalLinks(Document document) 3695 | { 3696 | // 过滤出所有的分析链接元素 3697 | FilteredElementCollector collectorAnalyticalLinks = new FilteredElementCollector(document); 3698 | collectorAnalyticalLinks.OfClass(typeof(AnalyticalLink)); 3699 | 3700 | IEnumerable alinks = collectorAnalyticalLinks. 3701 | ToElements().Cast(); 3702 | int nAutoGeneratedLinks = 0; 3703 | int nManualLinks = 0; 3704 | foreach (AnalyticalLink alink in alinks) 3705 | { 3706 | // 统计Revit自动创建的分析链接 3707 | if (alink.IsAutoGenerated() == true) 3708 | nAutoGeneratedLinks++; 3709 | else // 统计手动创建的分析链接 3710 | nManualLinks++; 3711 | } 3712 | string msg = "Auto-generated AnalyticalLinks: " + nAutoGeneratedLinks; 3713 | msg += "\nManually created AnalyticalLinks: " + nManualLinks; 3714 | TaskDialog.Show("AnalyticalLinks", msg); 3715 | } 3716 | 3717 | //============代码片段11-22:选择两个族实例创建分析链接============ 3718 | public void CreateLink(Document doc, FamilyInstance fi1, FamilyInstance fi2) 3719 | { 3720 | // 得到该Document里所有的分析节点 3721 | FilteredElementCollector hubCollector = new FilteredElementCollector(doc); 3722 | hubCollector.OfClass(typeof(Hub)); 3723 | ICollection allHubs = hubCollector.ToElements(); 3724 | // 得到第一个AnalyticalLinkType 3725 | FilteredElementCollector linktypeCollector = new FilteredElementCollector(doc); 3726 | linktypeCollector.OfClass(typeof(AnalyticalLinkType)); 3727 | ElementId firstLinkType = linktypeCollector.ToElementIds().First(); 3728 | 3729 | // 得到指定的族实例的分析节点 3730 | ElementId startHubId = GetHub(fi1.GetAnalyticalModel().Id, allHubs); 3731 | ElementId endHubId = GetHub(fi2.GetAnalyticalModel().Id, allHubs); 3732 | 3733 | Transaction tran = new Transaction(doc, "Create Link"); 3734 | tran.Start(); 3735 | // 通过指定两个分析节点来创建分析链接 3736 | AnalyticalLink createdLink = AnalyticalLink.Create(doc, firstLinkType, startHubId, endHubId); 3737 | tran.Commit(); 3738 | } 3739 | 3740 | /// 3741 | /// 获取指定的分析模型的第一个分析节点 3742 | /// 3743 | /// 分析模型 3744 | /// 分析节点集合 3745 | /// 返回指定的分析模型的第一个分析节点 3746 | private ElementId GetHub(ElementId hostId, ICollection allHubs) 3747 | { 3748 | foreach (Element ehub in allHubs) 3749 | { 3750 | Hub hub = ehub as Hub; 3751 | ConnectorManager manager = hub.GetHubConnectorManager(); 3752 | ConnectorSet connectors = manager.Connectors; 3753 | foreach (Connector connector in connectors) 3754 | { 3755 | ConnectorSet refConnectors = connector.AllRefs; 3756 | foreach (Connector refConnector in refConnectors) 3757 | { 3758 | if (refConnector.Owner.Id == hostId) 3759 | { 3760 | return hub.Id; 3761 | } 3762 | } 3763 | } 3764 | } 3765 | return ElementId.InvalidElementId; 3766 | } 3767 | 3768 | //============代码片段12-1 读写外观元素============ 3769 | public void GetAndSetMaterialAppearance(Document doc, Material mat, Asset anotherAsset) 3770 | { 3771 | ElementId assetElementId = mat.AppearanceAssetId; 3772 | if (assetElementId != ElementId.InvalidElementId) 3773 | { 3774 | // 获取材料的外观元素(AppearanceAssetElement)实例 3775 | AppearanceAssetElement appearanceElement = 3776 | doc.GetElement(assetElementId) as AppearanceAssetElement; 3777 | 3778 | // 读写外观的属性集合(Asset) 3779 | Asset currentAsset = appearanceElement.GetRenderingAsset(); 3780 | appearanceElement.SetRenderingAsset(anotherAsset); 3781 | } 3782 | 3783 | // 设置材料的外观元素。 3784 | FilteredElementCollector cotr = new FilteredElementCollector(doc); 3785 | IEnumerable allAppearanceElements = 3786 | cotr.OfClass(typeof(AppearanceAssetElement)).Cast(); 3787 | mat.AppearanceAssetId = allAppearanceElements.First().Id; 3788 | } 3789 | 3790 | //============代码片段12-2 加载外观元素到文档============ 3791 | public void LoadAndGetAllAppearanceAssets( 3792 | Autodesk.Revit.ApplicationServices.Application revitApp) 3793 | { 3794 | AssetSet theAssetSet = revitApp.get_Assets(AssetType.Appearance); 3795 | foreach (Asset theAsset in theAssetSet) 3796 | { 3797 | // 你可以在这里读取用API加载的外观元素了。 3798 | } 3799 | } 3800 | 3801 | //============代码片段12-3 创建材料的物理和热度============ 3802 | /// 3803 | /// Create a new brick material 3804 | /// 3805 | /// The specific material 3806 | private Material CreateSampleBrickMaterial() 3807 | { 3808 | SubTransaction createMaterial = new SubTransaction(this.m_document.Document); 3809 | createMaterial.Start(); 3810 | Material materialNew = null; 3811 | 3812 | //Try to copy an existing material. If it is not available, create a new one. 3813 | Material masonry_Brick = GetMaterial("Brick, Common"); 3814 | if (masonry_Brick != null) 3815 | { 3816 | materialNew = masonry_Brick.Duplicate(masonry_Brick.Name + "_new"); 3817 | System.Diagnostics.Debug.WriteLine(masonry_Brick.MaterialClass); 3818 | materialNew.MaterialClass = "Brick"; 3819 | } 3820 | else 3821 | { 3822 | ElementId idNew = Material.Create(m_document.Document, "New Brick Sample"); 3823 | materialNew = m_document.Document.GetElement(idNew) as Material; 3824 | materialNew.Color = new Autodesk.Revit.DB.Color(255, 0, 0); 3825 | } 3826 | createMaterial.Commit(); 3827 | 3828 | SubTransaction createPropertySets = new SubTransaction(this.m_document.Document); 3829 | createPropertySets.Start(); 3830 | 3831 | //Create a new structural asset and set properties on it. 3832 | StructuralAsset structuralAsssetBrick = new StructuralAsset("BrickStructuralAsset" , Autodesk.Revit.DB.StructuralAssetClass.Generic); 3833 | structuralAsssetBrick.DampingRatio = .5; 3834 | 3835 | PropertySetElement pseStructural = PropertySetElement.Create(m_document.Document, structuralAsssetBrick); 3836 | 3837 | 3838 | //Create a new thermal asset and set properties on it. 3839 | ThermalAsset thermalAssetBrick = new ThermalAsset("BrickThermalAsset", Autodesk.Revit.DB.ThermalMaterialType.Solid); 3840 | thermalAssetBrick.Porosity = 0.1; 3841 | thermalAssetBrick.Permeability = 0.2; 3842 | thermalAssetBrick.Compressibility = .5; 3843 | thermalAssetBrick.ThermalConductivity = .5; 3844 | 3845 | //Create PropertySets from assets and assign them to the material. 3846 | PropertySetElement pseThermal = PropertySetElement.Create(m_document.Document, thermalAssetBrick); 3847 | createPropertySets.Commit(); 3848 | SubTransaction setPropertySets = new SubTransaction(this.m_document.Document); 3849 | setPropertySets.Start(); 3850 | materialNew.SetMaterialAspectByPropertySet(MaterialAspect.Structural, pseStructural.Id); 3851 | materialNew.SetMaterialAspectByPropertySet(MaterialAspect.Thermal, pseThermal.Id); 3852 | 3853 | //also try 3854 | //materialNew.ThermalAssetId = pseThermal.Id; 3855 | 3856 | setPropertySets.Commit(); 3857 | return materialNew; 3858 | } 3859 | 3860 | //============代码片段12-4为墙体设置材料============ 3861 | public void GetAndSetMaterialForWall(Document doc, Wall wall, Material newMat) 3862 | { 3863 | // 得到墙体的复合结构(CompoundStructure)实例 3864 | WallType wallType = wall.WallType; 3865 | CompoundStructure wallCS = wallType.GetCompoundStructure(); 3866 | 3867 | // 得到墙体第一层材料的元素Id 3868 | CompoundStructureLayer firstLayer = wallCS.GetLayers().First(); 3869 | ElementId currentMatId = firstLayer.MaterialId; 3870 | 3871 | // 为墙体第一层设置一个新材料 3872 | firstLayer.MaterialId = newMat.Id; 3873 | } 3874 | 3875 | //============代码片段13-1:创建风管============ 3876 | public static Duct CreateDuct(Document doc) 3877 | { 3878 | ElementId systemTypeId, ductTypeId, levelId; 3879 | systemTypeId = ductTypeId = levelId = ElementId.InvalidElementId; 3880 | 3881 | // 获取标高Id 3882 | var levelFilter = new ElementClassFilter(typeof(Level)); 3883 | FilteredElementCollector levels = new FilteredElementCollector(doc); 3884 | levels = levels.WherePasses(levelFilter); 3885 | foreach (Level level in levels) 3886 | { 3887 | if (level.Name == "Level 1") 3888 | { 3889 | levelId = level.Id; 3890 | break; 3891 | } 3892 | } 3893 | if(levelId == ElementId.InvalidElementId) 3894 | throw new Exception("无法标高"); 3895 | 3896 | // 获取类型为SupplyAir的系统类型 3897 | var systemTypeFilter = new ElementClassFilter(typeof(MEPSystemType)); 3898 | FilteredElementCollector systemTypes = new FilteredElementCollector(doc); 3899 | systemTypes = systemTypes.WherePasses(systemTypeFilter); 3900 | List systypes = new List(); 3901 | foreach (MEPSystemType element in systemTypes) 3902 | { 3903 | if (element.SystemClassification == MEPSystemClassification.SupplyAir) 3904 | { 3905 | systemTypeId = element.Id; 3906 | break; 3907 | } 3908 | } 3909 | if (systemTypeId == ElementId.InvalidElementId) 3910 | throw new Exception("无法找到系统类型"); 3911 | 3912 | // 获取风管类型 3913 | var ductTypeFilter = new ElementClassFilter(typeof(DuctType)); 3914 | FilteredElementCollector ductTypes = new FilteredElementCollector(doc); 3915 | var result = ductTypes.WherePasses(ductTypeFilter).ToList(); 3916 | foreach (DuctType element in result) 3917 | { 3918 | ductTypeId = element.Id; 3919 | break; 3920 | } 3921 | 3922 | // 创建风管 3923 | using (Transaction transaction = new Transaction(doc)) 3924 | { 3925 | transaction.Start("创建风管"); 3926 | Duct duct = Duct.Create(doc, systemTypeId, ductTypeId, levelId, new XYZ(0, 10, 0), new XYZ(10, 0, 0)); 3927 | transaction.Commit(); 3928 | return duct; 3929 | } 3930 | } 3931 | 3932 | //============代码片段13-2:============ 3933 | public void GetElementAtConnector(Connector connector) 3934 | { 3935 | MEPSystem mepSystem = connector.MEPSystem; 3936 | if (null != mepSystem) 3937 | { 3938 | string message = "Connector is owned by: " + connector.Owner.Name; 3939 | if (connector.IsConnected == true) 3940 | { 3941 | ConnectorSet connectorSet = connector.AllRefs; 3942 | ConnectorSetIterator csi = connectorSet.ForwardIterator(); 3943 | while (csi.MoveNext()) 3944 | { 3945 | Connector connected = csi.Current as Connector; 3946 | if (null != connected) 3947 | { 3948 | // look for physical connections 3949 | if (connected.ConnectorType == ConnectorType.EndConn || 3950 | connected.ConnectorType == ConnectorType.CurveConn || 3951 | connected.ConnectorType == ConnectorType.PhysicalConn) 3952 | { 3953 | message += "\nConnector is connected to: " + connected.Owner.Name; 3954 | message += "\nConnection type is: " + connected.ConnectorType; 3955 | } 3956 | } 3957 | } 3958 | } 3959 | else 3960 | { 3961 | message += "\nConnector is not connected to anything."; 3962 | } 3963 | MessageBox.Show(message, "Revit"); 3964 | } 3965 | } 3966 | 3967 | //============代码片段13-3:创建弯头============ 3968 | public static void ConnectTwoDuctsWithElbow(Document doc, Duct duct1, Duct duct2) 3969 | { 3970 | double minDistance = double.MaxValue; 3971 | Connector connector1, connector2; 3972 | connector1 = connector2 = null; 3973 | 3974 | // 找到距离最近的两个Connector 3975 | foreach (Connector con1 in duct1.ConnectorManager.Connectors) 3976 | { 3977 | foreach (Connector con2 in duct2.ConnectorManager.Connectors) 3978 | { 3979 | var dis = con1.Origin.DistanceTo(con2.Origin); 3980 | if (dis < minDistance) 3981 | { 3982 | minDistance = dis; 3983 | connector1 = con1; 3984 | connector2 = con2; 3985 | } 3986 | } 3987 | } 3988 | if (connector1 != null && connector2 != null) 3989 | { 3990 | using (Transaction transaction = new Transaction(doc)) 3991 | { 3992 | transaction.Start("Create Elbow"); 3993 | doc.Create.NewElbowFitting(connector1, connector2); 3994 | transaction.Commit(); 3995 | } 3996 | } 3997 | } 3998 | 3999 | //============代码片段13-4:============ 4000 | public static void CreateMechanicalSystem(Document doc, DuctSystemType systemType, FamilyInstance equipment, params FamilyInstance[] airTerminals) 4001 | { 4002 | var me = equipment.MEPModel as MEPModel; 4003 | if (me != null) 4004 | { 4005 | // 获取符合条件的设备上的电气连接件 4006 | var connsOfEquipment = GetConnector(me.ConnectorManager, systemType).ToList(); 4007 | if (connsOfEquipment.Count > 0) 4008 | { 4009 | // 选取设备上的第一个电气连接件 4010 | var equipmentConn = connsOfEquipment[0]; 4011 | 4012 | var connsOfTerminals = new ConnectorSet(); 4013 | foreach (var terminal in airTerminals) 4014 | { 4015 | // 获取符合条件的散流器上的电气连接件,取第一个 4016 | var airTerminalEquipment = terminal.MEPModel as MEPModel; 4017 | var airConns = GetConnector(airTerminalEquipment.ConnectorManager, systemType); 4018 | var airConn = airConns.FirstOrDefault(); 4019 | if (airConn != null) 4020 | connsOfTerminals.Insert(airConn); 4021 | } 4022 | 4023 | // 创建风管系统 4024 | using (Transaction transaction = new Transaction(doc)) 4025 | { 4026 | transaction.Start("Create System"); 4027 | doc.Create.NewMechanicalSystem(equipmentConn, connsOfTerminals, systemType); 4028 | transaction.Commit(); 4029 | } 4030 | } 4031 | } 4032 | } 4033 | 4034 | // 获取符合管道系统的电气连接件 4035 | private static IEnumerable GetConnector(ConnectorManager conMgr, DuctSystemType systemType) 4036 | { 4037 | foreach (Connector conn in conMgr.Connectors) 4038 | { 4039 | // Domain为Hvac,否则DuctSystemType属性会抛出异常 4040 | if (conn.Domain == Domain.DomainHvac && conn.DuctSystemType == systemType) 4041 | { 4042 | yield return conn; 4043 | } 4044 | } 4045 | } 4046 | 4047 | //============代码片段13-5:============ 4048 | using (Transaction tran = new Transaction(doc, "DuctSettings")) 4049 | { 4050 | tran.Start(); 4051 | //获取Revit的风管设置对象 4052 | DuctSettings ductSettings = DuctSettings.GetDuctSettings(doc); 4053 | //设置风管设置的角度参数 4054 | ductSettings.FittingAngleUsage = FittingAngleUsage.UseAnAngleIncrement; 4055 | tran.Commit(); 4056 | } 4057 | 4058 | //============代码片段13-6:添加电压============ 4059 | using (Transaction tran = new Transaction(doc, "ElectricalSetting")) 4060 | { 4061 | tran.Start(); 4062 | //获取Revit的电气设置对象 4063 | ElectricalSetting electricalSettings = ElectricalSetting.GetElectricalSettings(doc); 4064 | //向电压定义参数中加入220伏电压 4065 | electricalSettings.AddVoltageType("220伏电压", 220, 220, 220); 4066 | tran.Commit(); 4067 | } 4068 | 4069 | //============代码片段13-7:创建分区和空间============ 4070 | using (Transaction tran = new Transaction(doc, "Create new space")) 4071 | { 4072 | tran.Start(); 4073 | Level level1 = doc.GetElement(new ElementId(311)) as Level; 4074 | Phase phase1 = doc.GetElement(new ElementId(86961)) as Phase; 4075 | //用时期(Phase)创建空间 4076 | Space space1 = doc.Create.NewSpace(phase1); 4077 | //用标高(Level)和平面的点创建空间 4078 | Space space2 = doc.Create.NewSpace(level1, new UV(-31, -19)); 4079 | //用时期(Phase),标高(Level)和平面的点创建空间 4080 | Space space3 = doc.Create.NewSpace(level1, phase1, new UV(4, 16)); 4081 | //用标高(Level)和时期(Phase)创建分区 4082 | Zone zone1 = doc.Create.NewZone(level1, phase1); 4083 | SpaceSet spaceSet = new SpaceSet(); 4084 | spaceSet.Insert(space1); 4085 | spaceSet.Insert(space2); 4086 | spaceSet.Insert(space3); 4087 | //将空间添加到分区中 4088 | zone1.AddSpaces(spaceSet); 4089 | tran.Commit(); 4090 | } 4091 | 4092 | //============代码片段14-1:创建一个文字注释元素============ 4093 | public void MyFirstMacroAppCS() 4094 | { 4095 | Autodesk.Revit.DB.XYZ baseVec = Application.Create.NewXYZ(1.0, 0.0, 0.0); 4096 | Autodesk.Revit.DB.XYZ upVec = Application.Create.NewXYZ(0.0, 0.0, 1.0); 4097 | Autodesk.Revit.DB.XYZ origin = Application.Create.NewXYZ(0.0, 0.0, 0.0); 4098 | 4099 | Autodesk.Revit.DB.TextAlignFlags align = Autodesk.Revit.DB.TextAlignFlags.TEF_ALIGN_LEFT | Autodesk.Revit.DB.TextAlignFlags.TEF_ALIGN_TOP; 4100 | 4101 | string strText = "My First Macro, App level, C#!"; 4102 | double lineWidth = 4.0 / 12.0; 4103 | 4104 | Autodesk.Revit.DB.View pView = ActiveUIDocument.Document.ActiveView; 4105 | Autodesk.Revit.DB.Transaction t = new Autodesk.Revit.DB.Transaction(ActiveUIDocument.Document, "NewTextNote"); 4106 | t.Start(); 4107 | ActiveUIDocument.Document.Create.NewTextNote(pView, origin, baseVec, upVec, lineWidth, align, strText); 4108 | 4109 | t.Commit(); 4110 | } 4111 | 4112 | //============代码片段14-2:创建一个文字注释元素(C#)============ 4113 | public void MyFirstMacroAppCS() 4114 | { 4115 | Autodesk.Revit.DB.XYZ baseVec = Application.Create.NewXYZ(1.0, 0.0, 0.0); 4116 | Autodesk.Revit.DB.XYZ upVec = Application.Create.NewXYZ(0.0, 0.0, 1.0); 4117 | Autodesk.Revit.DB.XYZ origin = Application.Create.NewXYZ(0.0, 0.0, 0.0); 4118 | 4119 | Autodesk.Revit.DB.TextAlignFlags align = Autodesk.Revit.DB.TextAlignFlags.TEF_ALIGN_LEFT | Autodesk.Revit.DB.TextAlignFlags.TEF_ALIGN_TOP; 4120 | 4121 | string strText = "My First Macro, App level, C#!"; 4122 | double lineWidth = 4.0 / 12.0; 4123 | 4124 | Autodesk.Revit.DB.View pView = ActiveUIDocument.Document.ActiveView; 4125 | Autodesk.Revit.DB.Transaction t = new Autodesk.Revit.DB.Transaction(ActiveUIDocument.Document, "NewTextNote"); 4126 | t.Start(); 4127 | ActiveUIDocument.Document.Create.NewTextNote(pView, origin, baseVec, upVec, lineWidth, align, strText); 4128 | 4129 | t.Commit(); 4130 | } 4131 | 4132 | //============代码片段14-3:创建一个文字注释元素(VB.NET)============ 4133 | Public Sub MyFirstMacroAppVB() 4134 | Dim baseVec As Autodesk.Revit.DB.XYZ = Application.Create.NewXYZ(1.0, 0.0, 0.0) 4135 | Dim upVec As Autodesk.Revit.DB.XYZ = Application.Create.NewXYZ(0.0, 0.0, 1.0) 4136 | Dim origin As Autodesk.Revit.DB.XYZ = Application.Create.NewXYZ(0.0, 0.0, 0.0) 4137 | Dim align As Autodesk.Revit.DB.TextAlignFlags = Autodesk.Revit.DB.TextAlignFlags.TEF_ALIGN_LEFT Or Autodesk.Revit.DB.TextAlignFlags.TEF_ALIGN_TOP 4138 | Dim strText As String = "My First Macro, App Level, VB.NET!" 4139 | Dim lineWidth As Double = 4.0 / 12.0 4140 | Dim pView As Autodesk.Revit.DB.View = ActiveUIDocument.Document.ActiveView 4141 | Dim Transaction As Autodesk.Revit.DB.Transaction = New Autodesk.Revit.DB.Transaction(ActiveUIDocument.Document, "NewTextNote") 4142 | Transaction.Start() 4143 | ActiveUIDocument.Document.Create.NewTextNote(pView, origin, baseVec, upVec, lineWidth, align, strText) 4144 | Transaction.Commit() 4145 | End Sub 4146 | 4147 | //============代码片段14-4:显示版本和文件标题(Ruby)============ 4148 | def SampleMacroImplementation() 4149 | revitVersion = self.Application.VersionBuild 4150 | docTitle = "" 4151 | if (self.ActiveUIDocument.Document!= nil) 4152 | docTitle = self.ActiveUIDocument.Document.Title 4153 | end 4154 | TaskDialog.Show("Ruby Sample", "Revit Version: " + revitVersion + ", Document title: " + docTitle) 4155 | end 4156 | 4157 | //============代码片段14-5:显示版本和文件标题(Python)============ 4158 | def SampleMacro(self): 4159 | revitVersion = self.Application.VersionBuild 4160 | docTitle = "" 4161 | if (self.ActiveUIDocument.Document!= None): 4162 | docTitle = self.ActiveUIDocument.Document.Title; 4163 | TaskDialog.Show("Python Sample", "Revit Version: " + revitVersion + ", Document title: " + docTitle) 4164 | 4165 | //============代码片段14-6:创建一个文字注释元素(C#)============ 4166 | public void MyFirstMacroDocCS() 4167 | { 4168 | Autodesk.Revit.DB.XYZ baseVec = Document.Application.Create.NewXYZ(0.0, 0.0, 1.0); 4169 | Autodesk.Revit.DB.XYZ upVec = Document.Application.Create.NewXYZ(0.0, 0.0, 1.0); 4170 | Autodesk.Revit.DB.XYZ origin = Document.Application.Create.NewXYZ(0.0, 0.0, 0.0); 4171 | Autodesk.Revit.DB.TextAlignFlags align = Autodesk.Revit.DB.TextAlignFlags.TEF_ALIGN_LEFT | Autodesk.Revit.DB.TextAlignFlags.TEF_ALIGN_TOP; 4172 | string strText = "My First Macro, Doc level, C#!"; 4173 | double lineWidth = 4.0 / 12.0; 4174 | Autodesk.Revit.DB.Transaction t = new Autodesk.Revit.DB.Transaction(Document, "NewTextNote"); 4175 | t.Start(); 4176 | Autodesk.Revit.DB.View pView = Document.ActiveView; 4177 | Document.Create.NewTextNote(pView, origin, baseVec, upVec, lineWidth, align, strText); 4178 | t.Commit(); 4179 | } 4180 | 4181 | //============代码片段14-7:创建一个文字注释元素(VB.NET)============ 4182 | Public Sub MyFirstMacroDocVB() 4183 | Dim baseVec As Autodesk.Revit.DB.XYZ = Document.Application.Create.NewXYZ(1.0, 0.0, 0.0) 4184 | Dim upVec As Autodesk.Revit.DB.XYZ = Document.Application.Create.NewXYZ(0.0, 0.0, 1.0) 4185 | Dim origin As Autodesk.Revit.DB.XYZ = Document.Application.Create.NewXYZ(0.0, 0.0, 0.0) 4186 | Dim align As Autodesk.Revit.DB.TextAlignFlags = Autodesk.Revit.DB.TextAlignFlags.TEF_ALIGN_LEFT Or Autodesk.Revit.DB.TextAlignFlags.TEF_ALIGN_TOP 4187 | Dim strText As String = "My First Macro, Doc Level, VB.NET!" 4188 | Dim lineWidth As Double = 4.0 / 12.0 4189 | Dim pView As Autodesk.Revit.DB.View = Document.ActiveView 4190 | Dim Transaction As Autodesk.Revit.DB.Transaction = New Autodesk.Revit.DB.Transaction(Document, "NewTextNote") 4191 | Transaction.Start() 4192 | Document.Create.NewTextNote(pView, origin, baseVec, upVec, lineWidth, align, strText) 4193 | Transaction.Commit() 4194 | End Sub 4195 | 4196 | //============代码片段14-8:显示版本和文件标题(Ruby)============ 4197 | def SampleMacroImplementation() 4198 | revitVersion = self.Application.Application.VersionBuild 4199 | docTitle = "" 4200 | if (self.Document!= nil) 4201 | docTitle = self.Document.Title 4202 | end 4203 | TaskDialog.Show("Ruby Sample", "Revit Version: " + revitVersion + ", Document title: " + docTitle) 4204 | end 4205 | 4206 | //============代码片段14-9:显示版本和文件标题(Python)============ 4207 | def SampleMacro(self): 4208 | revitVersion = self.Application.Application.VersionBuild 4209 | docTitle = "" 4210 | if (self.Document!= None): 4211 | docTitle = self.Document.Title; 4212 | TaskDialog.Show("Python Sample", "Revit Version: " + revitVersion + ", Document title: " + docTitle) 4213 | 4214 | //============代码片段15-1:HelloRevit(VB.NET)============ 4215 | Imports System 4216 | 4217 | Imports Autodesk 4218 | Imports Autodesk.Revit.DB 4219 | Imports Autodesk.Revit.UI 4220 | Imports Autodesk.Revit.ApplicationServices 4221 | 4222 | _ 4223 | Public Class Command 4224 | Implements Autodesk.Revit.UI.IExternalCommand 4225 | 4226 | Public Function Execute(ByVal commandData As Autodesk.Revit.UI.ExternalCommandData, _ 4227 | ByRef message As String, ByVal elements As Autodesk.Revit.DB.ElementSet) _ 4228 | As Autodesk.Revit.UI.Result Implements Autodesk.Revit.UI.IExternalCommand.Execute 4229 | 4230 | Dim app As Application 4231 | app = commandData.Application.Application 4232 | Dim activeDoc As Document 4233 | activeDoc = commandData.Application.ActiveUIDocument.Document 4234 | Dim mainDialog As TaskDialog 4235 | mainDialog = New TaskDialog("Hello, Revit!") 4236 | mainDialog.MainInstruction = "Hello, Revit!" 4237 | mainDialog.MainContent = _ 4238 | "This sample shows how a basic ExternalCommand can be added to the Revit user interface." _ 4239 | + " It uses a Revit task dialog to communicate information to the interactive user.\n" 4240 | mainDialog.Show() 4241 | Return Autodesk.Revit.UI.Result.Succeeded 4242 | End Function 4243 | End Class 4244 | 4245 | //============代码片段15-2:HelloRevit.addin文件============ 4246 | 4247 | 4248 | 4249 | HelloRevit.dll 4250 | 0e6385db-b2c0-4397-8702-b1b889bad37c 4251 | HelloRevit.Class1 4252 | ADSK 4253 | 4254 | 4255 | 4256 | //============代码片段15-3:HelloRevit.h============ 4257 | #pragma once 4258 | 4259 | using namespace System; 4260 | 4261 | using namespace Autodesk::Revit; 4262 | using namespace Autodesk::Revit::DB; 4263 | using namespace Autodesk::Revit::UI; 4264 | using namespace Autodesk::Revit::ApplicationServices; 4265 | 4266 | namespace HelloRevit { 4267 | 4268 | public ref class Class1 : IExternalCommand 4269 | { 4270 | public: 4271 | virtual Result Execute(ExternalCommandData^ commandData, String^% message, ElementSet^ elements); 4272 | }; 4273 | } 4274 | 4275 | //============代码片段15-4:HelloRevit.cpp============ 4276 | #include "stdafx.h" 4277 | 4278 | #include "HelloRevit.h" 4279 | 4280 | namespace HelloRevit 4281 | { 4282 | Result Class1::Execute(ExternalCommandData^ commandData, String^% message, ElementSet^ elements) 4283 | { 4284 | Application^ app = commandData->Application->Application; 4285 | Document^ activeDoc = commandData->Application->ActiveUIDocument->Document; 4286 | TaskDialog^ mainDialog = gcnew TaskDialog("Hello, Revit!"); 4287 | mainDialog->MainInstruction = "Hello, Revit!"; 4288 | mainDialog->MainContent = "This sample shows how a basic ExternalCommand can be added to the Revit user interface. It uses a Revit task dialog to communicate information to the interactive user."; 4289 | mainDialog->Show(); 4290 | return Autodesk::Revit::UI::Result::Succeeded; 4291 | } 4292 | } 4293 | 4294 | //============代码片段15-5:HelloRevit.addin文件============ 4295 | 4296 | 4297 | 4298 | HelloRevit.dll 4299 | 0e6385db-b2c0-4397-8702-b1b889bad37c 4300 | HelloRevit.Class1 4301 | ADSK 4302 | 4303 | 4304 | 4305 | //============代码片段15-6:HelloRevit.h============ 4306 | module Module1 4307 | 4308 | open Autodesk.Revit 4309 | open Autodesk.Revit.UI 4310 | open Autodesk.Revit.Attributes 4311 | open Autodesk.Revit.DB 4312 | 4313 | [] 4314 | type Class1 = 4315 | interface Autodesk.Revit.UI.IExternalCommand with 4316 | member this.Execute(commandData, 4317 | message : string byref, 4318 | elements ) = 4319 | let uiApp = commandData.Application 4320 | let app = uiApp.Application 4321 | let uiDoc = uiApp.ActiveUIDocument 4322 | let doc = uiDoc.Document 4323 | 4324 | use mainDialog = new TaskDialog("Hello, Revit!") 4325 | mainDialog.MainInstruction <- "This sample shows how a basic ExternalCommand can be added to the Revit user interface. It uses a Revit task dialog to communicate information to the interactive user." 4326 | let result = mainDialog.Show() 4327 | Autodesk.Revit.UI.Result.Succeeded 4328 | 4329 | //============代码片段15-7:HelloRevit.addin文件============ 4330 | 4331 | 4332 | 4333 | HelloRevit.dll 4334 | 1585c811-3dc4-43f4-9ec5-e7e695a6ff72 4335 | HelloRevit.Class1 4336 | ADSK 4337 | 4338 | 4339 | 4340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Revitapi Tutorial Book - Chinese Version 2 | 这里是《Autodesk Revit 二次开发基础教程》代码示例以及一些补充说明。 3 | * 代码示例请见CodeSnippets.cs文件 4 | * 本书在写作的过程中难免有一些疏漏之处,请大家谅解。如果有发现任何新的问题,请联系我们Aaron.Lu@autodesk.com或revitdevelopers@sina.com或者直接在github上提交一个问题,方法是:点击Issues,再点击Create an issue,然后发布该问题。 5 | * [点击这里直通购买地址](https://detail.tmall.com/item.htm?spm=a1z10.5-b.w4011-7642016013.86.kqSuts&id=521852354085&rn=9ca0adf9fcbae2111fa480ccec7d15ef&abbucket=19) 6 | * RevitSDK的下载地址:[http://www.autodesk.com/developrevit](http://www.autodesk.com/developrevit) 7 | 8 | ## 第一版的一些修正 9 | 第一版于2015年9月中旬出版,下面是一些需要修正的地方: 10 | * `P5` Revit® API.dll和Revit® APIUI.dll,应该是RevitAPI.dll和RevitAPIUI.dll 11 | * `P6` 图2-2中的Revit.ini,应该是.addin 12 | * `P11` 代码片段2-8中,应该是 13 | ```C# 14 | Autodesk.Revit.DB.ExternalDBApplicationResult OnShutdown(UIControlledApplication application); 15 | Autodesk.Revit.DB.ExternalDBApplicationResult OnStartup(UIControlledApplication application); 16 | ``` 17 | * `P19` 表2-6中,应该是 18 | ```C# 19 | Document NewFamilyDocument 20 | Document NewProjectDocument 21 | Document NewProjectTemplateDocument 22 | ``` 23 | * `P28` Visual Studio 2010,应该是Visual Studio 2012 24 | * `P30` C:\Program Files\Revit Architecture 2014\Program\Revit.exe,应该是C:\Program Files\Revit 2015\Revit.exe 25 | * `P32` 代码片段2-26:由于需要使用BitmapImage等类,所以要引用这几个dll:WindowsBase, PresentationCore, System.Xaml 26 | * `P55` 图3-13,3-14中的Matg.PI,应该是Math.PI 27 | * `P89` "代码片段4-11:创建三角形墙",这里的"墙"应该改为"板" 28 | * `P136` 表6-3描述里面的ViewSectiono, 应该是ViewSection 29 | --------------------------------------------------------------------------------