using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB.Structure;
namespace 遍历CAD上所有类型的线段
{
[Transaction(TransactionMode.Manual)]
public class Class1 : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
UIDocument uidoc = commandData.Application.ActiveUIDocument;
Document doc = uidoc.Document;//获取活动文档
Selection sel = uidoc.Selection;
Reference re = sel.PickObject(ObjectType.PointOnElement);//获取到CAD上的reference
ImportInstance dwg = doc.GetElement(re) as ImportInstance;//cad引用转换为导入实例
//创建几何选项
Options opt = new Options();
opt.ComputeReferences = true;
//Options.ComputeReferences必须为true,否是拿到的几何体的Reference都将是null
opt.DetailLevel = ViewDetailLevel.Fine;
GeometryElement e = dwg.get_Geometry(opt);
//获取CAD上的线并生成模型线
Transaction trans = new Transaction(doc, "创建模型线");
trans.Start();
//隐藏CAD
var geoObj = (dwg as Element).GetGeometryObjectFromReference(re);//获取几何对象
ElementId ElId = null;
GraphicsStyle _graphicsStyle = doc.GetElement(geoObj.GraphicsStyleId) as GraphicsStyle;//获取图形类型
ElId = _graphicsStyle.GraphicsStyleCategory.Id;//获取图形类别的ID
doc.ActiveView.SetCategoryHidden(ElId, true);//设置类别隐藏
foreach (GeometryObject obj in e)
{
if (obj is GeometryInstance)//对象是geometryinstance
{
GeometryInstance geoInstance = obj as GeometryInstance;
GeometryElement geoElement = geoInstance.GetInstanceGeometry();
foreach (GeometryObject obj2 in geoElement)
{
ElementId obj2Id = (doc.GetElement(obj2.GraphicsStyleId) as GraphicsStyle).GraphicsStyleCategory.Id;//获取图形类别ID
if (obj2Id == ElId)//判断选择类别ID和图层ID是否匹配
{
List<XYZ> xyzList = new List<XYZ>();
if (obj2 is PolyLine)
{
PolyLine pLine = obj2 as PolyLine;
foreach (XYZ p in pLine.GetCoordinates())
{
xyzList.Add(p);
}
CreatModelCurve(doc, xyzList);
}
if (obj2 is Arc)
{
}
if (obj2 is Line)
{
Line line = obj2 as Line;
foreach (XYZ p in line.Tessellate())
{
xyzList.Add(p);
}
CreatModelCurve(doc, xyzList);
}
}
}
}
}
trans.Commit();
return Result.Succeeded;
}
/// <summary>
///
/// </summary>
/// <param name="doc">文档</param>
/// <param name="xyzList">传入点列表</param>
private void CreatModelCurve(Document doc, List<XYZ> xyzList)
{
SketchPlane modelSketch = SketchPlane.Create(doc, Plane.CreateByNormalAndOrigin(XYZ.BasisZ, XYZ.Zero));
for (int i = 0; i < xyzList.Count; i++)
{
if (i >= 1)
{
Line line = Line.CreateBound(xyzList[i], xyzList[i - 1]);
ModelCurve modelLine = doc.Create.NewModelCurve(line, modelSketch);
}
}
}
}
}
这里要感谢一下CSDN niuge8905版主 https://blog.csdn.net/niuge8905/article/details/77160646 和 JohnnyWu0918 https://me.csdn.net/mye918 从他们的文章中找到了读取CAD线段的一些方法。