在Revit API中加载族可以使用Doc.LoadFamily要领,传入要加载的族文件路径名,但是这种方法有一种错误谬误,就是如果族文件在当前工程中没有加载的话则返回告成,如果已经加载过,,则返回掉败,也就是拿不到FamilySymbol实例,而按照族生成实例图元又需要这个FamilySymbol。网上看到有些帖子说可以传入IFamilyLoadOptions实例就可以,但是笔者多次测验考试,该要领均没有告成,始终返回掉败,无奈放弃这种要领,改为在当前工程中查找该族是否加载过,如果加载则直接返回FamilySymbol实例,否则加载族文件,下面贴出代码。
该代码在Revit 2016 + VS2013下调试通过:
public class CreateFamilyInstance : IExternalCommand { private class FamilyLoadOptions : IFamilyLoadOptions { public bool OnFamilyFound(bool familyInUse, out bool overwriteParameterValues) { overwriteParameterValues = true; return true; } public bool OnSharedFamilyFound(Family sharedFamily, bool familyInUse, out FamilySource source, out bool overwriteParameterValues) { source = FamilySource.Family; overwriteParameterValues = true; return true; } } private FamilySymbol FindFamilySymbol(Document rvtDoc, string familyName, string symbolName) { FilteredElementCollector collector = new FilteredElementCollector(rvtDoc); FilteredElementIterator itr = collector.OfClass(typeof(Family)).GetElementIterator(); itr.Reset(); while (itr.MoveNext()) { Autodesk.Revit.DB.Element elem = (Autodesk.Revit.DB.Element)itr.Current; if (elem.GetType() == typeof(Autodesk.Revit.DB.Family)) { if (elem.Name == familyName) { Autodesk.Revit.DB.Family family = (Autodesk.Revit.DB.Family)elem; foreach (Autodesk.Revit.DB.ElementId symbolId in family.GetFamilySymbolIds()) { Autodesk.Revit.DB.FamilySymbol symbol = (Autodesk.Revit.DB.FamilySymbol)rvtDoc.GetElement(symbolId); if (symbol.Name == symbolName) { return symbol; } } } } } return null; } public Autodesk.Revit.UI.Result Execute(ExternalCommandData cmdData, ref string message, Autodesk.Revit.DB.ElementSet elements) { UIApplication app = cmdData.Application; Document doc = app.ActiveUIDocument.Document; Transaction trans = new Transaction(doc, "ExComm"); trans.Start(); Family fs = null; FamilySymbol symbol = null; doc.LoadFamily(@"C:\\ProgramData\\Autodesk\\RVT 2016\\Libraries\\China\\布局\\柱\\混凝土\\混凝土柱-T形.rfa", new FamilyLoadOptions(), out fs); if (fs != null) { foreach (ElementId symbolId in fs.GetFamilySymbolIds()) { Element elem = doc.GetElement(symbolId); if (null != elem) { symbol = elem as FamilySymbol; if (null != symbol) { TaskDialog.Show("Info", symbol.Name); TaskDialog.Show("Info", symbol.FamilyName); break; } } } } else { symbol = FindFamilySymbol(doc, "混凝土柱-T形", "标准"); if (null != symbol) { TaskDialog.Show("Info", symbol.Name); TaskDialog.Show("Info", symbol.FamilyName); } } if (null != symbol) { if (!symbol.IsActive) symbol.Activate(); XYZ point = new XYZ(10, 10, 10); //创建族实例 FamilyInstance fi = doc.Create.NewFamilyInstance(point, symbol, Autodesk.Revit.DB.Structure.StructuralType.Column); } else { TaskDialog.Show("erorr", "FamilySymbol为空"); } trans.Commit(); return Autodesk.Revit.UI.Result.Succeeded; } }
Revit API 加载族并生成实例图元