Revit开发小功能集合

文章目录

      • 1.获取Revit中打开的所有的View(视图)
      • 2.在不打开Revit的情况下读取rvt文件数据
      • 3.获取元素的材质信息
      • 5.编辑族参数(没有成功,后期会更新)
      • 6.访问墙体结构层信息
      • 7.取消选中元素
      • 8.选中元素
      • 9获取元素的几何信息
      • 10 预览Revit视图的控件
      • 11 对元素的基本操作

1.获取Revit中打开的所有的View(视图)

using System;
using System.Collections.Generic;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.UI.Selection;
namespace 插件
{
    [Autodesk.Revit.Attributes.Transaction(TransactionMode.Manual)]
    public class Command:IExternalCommand
    {
        /// 
        /// 获取所有打开的视图并返回视图名称
        /// 
        /// 
        /// 
        private string GetOPenViews(UIDocument uidoc)
        {
            string info = null;
            IList<UIView> views = uidoc.GetOpenUIViews();
            foreach(UIView view in views)
            {
                info += uidoc.Document.GetElement(view.ViewId).Name+"\n";
            }
            return info;
        }
        public Result Execute(ExternalCommandData commandData,ref string message,ElementSet elementSet)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document doc = uidoc.Document;
            Selection selection = uidoc.Selection;
            try
            {
                string res = GetOPenViews(uidoc);
                TaskDialog.Show("OpenViews", $"{res}");
                return Result.Succeeded;
            }
            catch(Exception ex)
            {
                TaskDialog.Show("Error Info", $"{ex.Message}");
                return Result.Failed;
            }
        }

    }
}


2.在不打开Revit的情况下读取rvt文件数据

在Revit插件中可以在后台打开rvt文件,并且访问他的数据,但是这个数据读取时依赖于Revit软件的。
就是说必须要在Revit打开的情况下,运行一个插件,在插件代码里读取rvt 的信息
我准备了一个机电测试文件,这个项目文件里面一共画了三个构建:一个长度为8800mm的风管,一个长度为6600mm的水管和一个桥架

下面的例子实现了打开一个rvt文件,并且过滤其中的风管类型的构建,并且获取风管实例的长度,结果确实是8800mm

using System;
using System.Collections.Generic;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.UI.Selection;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.DB.Electrical;
namespace 插件
{
    [Autodesk.Revit.Attributes.Transaction(TransactionMode.Manual)]
    public class Command:IExternalCommand
    {
        public Result Execute(ExternalCommandData commandData,ref string message,ElementSet elementSet)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document doc = uidoc.Document;
            Selection selection = uidoc.Selection;

            Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application;
            Document _doc = app.OpenDocumentFile(@"D:\revit development project\Revit开发\机电测试.rvt");
            try
            {
                FilteredElementCollector filter = new FilteredElementCollector(_doc);
                filter.OfCategory(BuiltInCategory.OST_DuctCurves).WhereElementIsNotElementType();
                foreach(Element elem in filter)
                {
                    LocationCurve lc = elem.Location as LocationCurve;
                    TaskDialog.Show("Info",$"风管的长度={lc.Curve.Length*304.8}");
                }

                return Result.Succeeded;
            }
            catch(Exception ex)
            {
                TaskDialog.Show("Error Info", $"{ex.Message}");
                return Result.Failed;
            }
        }

    }
}


3.获取元素的材质信息

using System;
using System.Collections.Generic;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.UI.Selection;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.DB.Electrical;
namespace 插件
{
    [Autodesk.Revit.Attributes.Transaction(TransactionMode.Manual)]
    public class Command : IExternalCommand
    {
        public readonly double unit = 304.8;
        /// 
        /// 用一个轮廓来创建墙体,可以按照提供的轮廓创建形状比较灵活的墙体,这里创建一个梯形墙体
        /// 
        /// 
        public Wall CreateWall1(Document doc)
        {
            IList<Curve> curves = new List<Curve>();
            Line l1 = Line.CreateBound(XYZ.Zero, new XYZ(150, 0, 0));
            Line l2 = Line.CreateBound(XYZ.Zero, new XYZ(50, 0, 50));
            Line l3 = Line.CreateBound(new XYZ(50, 0, 50), new XYZ(100, 0, 50));
            Line l4 = Line.CreateBound(new XYZ(100, 0, 50), new XYZ(150, 0, 0));
            curves.Add(l1);
            curves.Add(l2);
            curves.Add(l3);
            curves.Add(l4);
            Wall wall1 = Wall.Create(doc, curves, false);
            return wall1;
        }
        /// 
        /// 根据墙体的投影线,标高来创建墙体
        /// 
        /// 
        public Wall CreateWall2(Document doc)
        {
            // 创建一个轮廓,只需要创建墙体在x-o-y平面的投影就可以
            Curve curve1 = Line.CreateBound(XYZ.Zero, new XYZ(2000/unit, 0, 0)) as Curve;
            #region 找出标高最低的标高
            FilteredElementCollector coll = new FilteredElementCollector(doc);
            coll.OfCategory(BuiltInCategory.OST_Levels).WhereElementIsNotElementType();
            List<Level> levels = new List<Level>();
            foreach (Level item in coll)
            {
                levels.Add(item);
            }
            levels.Sort((Level l1, Level l2) => l1.Elevation.CompareTo(l2.Elevation));
            #endregion

            //找出一个墙体类型
            FilteredElementCollector coll_wall = new FilteredElementCollector(doc).OfClass(typeof(WallType));
            ElementId levelId;
            ElementId wallTypeId;
            Level level = levels[0];
            if (level != null)
            {
                levelId = level.Id;
            }
            else
            {
                throw new Exception("标高为空");
            }

            WallType type = coll_wall.FirstElement() as WallType;
            if (type != null)
            {
                wallTypeId = type.Id;
            }
            else
            {
                throw new Exception("墙体类型为空");
            }

            Wall wall2 = Wall.Create(doc, curve1, levels[0].Id, false);
            return wall2;
        }

        /// 
        /// 根据墙体的投影线,标高,墙体类型,偏移量,墙体高度创建墙体
        /// 
        /// 
        /// 
        public Wall CreateWall3(Document doc)
        {
            // 定义墙体的高度和偏移量
            double wall_height = 3000 / unit;
            double wall_offset = 300 / unit;
            // 创建一个轮廓,只需要创建墙体在x-o-y平面的投影就可以
            Curve curve1 = Line.CreateBound(XYZ.Zero, new XYZ(2000 / unit, 0, 0)) as Curve;
            #region 找出标高最低的标高
            FilteredElementCollector coll = new FilteredElementCollector(doc);
            coll.OfCategory(BuiltInCategory.OST_Levels).WhereElementIsNotElementType();
            List<Level> levels = new List<Level>();
            foreach (Level item in coll)
            {
                levels.Add(item);
            }
            levels.Sort((Level l1, Level l2) => l1.Elevation.CompareTo(l2.Elevation));
            #endregion

            //找出一个墙体类型
            FilteredElementCollector coll_wall = new FilteredElementCollector(doc).OfClass(typeof(WallType));
            ElementId levelId;
            ElementId wallTypeId;
            Level level = levels[0];
            if (level != null)
            {
                levelId = level.Id;
            }
            else
            {
                throw new Exception("标高为空");
            }

            WallType type = coll_wall.FirstElement() as WallType;
            if (type != null)
            {
                wallTypeId = type.Id;
            }
            else
            {
                throw new Exception("墙体类型为空");
            }

            Wall wall2 = Wall.Create(doc,curve1,wallTypeId,levelId,wall_height,wall_offset,false,false);
            return wall2;

        }

        /// 
        /// 需要的参数是前三种方法的不同组合就不写了
        /// 
        /// 
        public Wall CreateWall4(Document doc)
        {
            //需要的参数是前三种方法的不同组合就不写了
            return null;
        }
        /// 
        /// 需要的参数是前三种方法的不同组合就不写了
        /// 
        /// 
        public Wall CreateWall5(Document doc)
        {
            //需要的参数是前三种方法的不同组合就不写了
            return null;
        }

        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elementSet)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document doc = uidoc.Document;
            Selection selection = uidoc.Selection;
            try
            {
                using (Transaction ts = new Transaction(doc, "创建墙体"))
                {
                    ts.Start();
                    //CreateWall1(doc);
                    //CreateWall2(doc);
                    //CreateWall3(doc);
                    ts.Commit();
                }
                return Result.Succeeded;
            }
            catch(Exception ex)
            {
                throw new Exception(ex.StackTrace);
            }
        }

    }
}


5.编辑族参数(没有成功,后期会更新)

注意:只有载入的族才是可以修改的
using System;
using System.Collections.Generic;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.UI.Selection;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.DB.Electrical;
namespace 插件
{
    [Autodesk.Revit.Attributes.Transaction(TransactionMode.Manual)]
    [Autodesk.Revit.Attributes.Regeneration(RegenerationOption.Manual)]
    [Autodesk.Revit.Attributes.Journaling(JournalingMode.UsingCommandData)]
    public class Command : IExternalCommand
    {
        public readonly double unit = 304.8;

        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elementSet)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document doc = uidoc.Document;
            Selection selection = uidoc.Selection;
            Reference reff = selection.PickObject(ObjectType.Element);
            Element elem = doc.GetElement(reff);

            //返回familySymbol的Id
            ElementId id = elem.GetTypeId();
            FamilySymbol fmSymbol = doc.GetElement(id) as FamilySymbol;

            // 返回编辑族的Document
            Document fmDoc = doc.EditFamily(fmSymbol.Family);


            // 得到FamilyManager,关于族参数的操作都在里面
            FamilyManager manager = fmDoc.FamilyManager;
            IList<FamilyParameter> parameters = manager.GetParameters();
            string info = string.Empty;
            for(int i=0;i<parameters.Count;i++)
            {
                info += parameters[i].Definition.Name + "\n";
            }
            TaskDialog.Show("Parameter",info);
            Transaction ts = new Transaction(doc, "创建墙体");
            ts.Start();
          //  manager.RemoveParameter(parameters[-4]);
            manager.AddParameter("gender", BuiltInParameterGroup.PG_IDENTITY_DATA, ParameterType.Text, false);
          
            ts.Commit();
            fmDoc.LoadFamily(doc, new Opt());

            return Result.Succeeded;
        }

    }
    public class Opt : 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)
        {
            throw new NotImplementedException();
        }
    }
}

6.访问墙体结构层信息

using System;
using System.Collections.Generic;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.UI.Selection;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.DB.Electrical;
namespace 插件
{
    [Autodesk.Revit.Attributes.Transaction(TransactionMode.Manual)]
    [Autodesk.Revit.Attributes.Regeneration(RegenerationOption.Manual)]
    [Autodesk.Revit.Attributes.Journaling(JournalingMode.UsingCommandData)]
    public class Command : IExternalCommand
    {
        public readonly double unit = 304.8;

        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elementSet)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document doc = uidoc.Document;
            Selection selection = uidoc.Selection;

            Reference reff = selection.PickObject(ObjectType.Element, "please select a wall");
            Wall wall = doc.GetElement(reff) as Wall;
            string info = string.Empty;
            CompoundStructure compoundStructure = wall.WallType.GetCompoundStructure();
            foreach(CompoundStructureLayer item in compoundStructure.GetLayers())
            {
                if (item.MaterialId == ElementId.InvalidElementId) continue;
                Material m = doc.GetElement(item.MaterialId) as Material;
                if (m == null) continue;
                info += m.Name + "\n";
            }

            TaskDialog.Show("墙体结构材质",info);
            return Result.Succeeded;
        }
    }
}

7.取消选中元素

using System;
using System.Collections.Generic;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.UI.Selection;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.DB.Electrical;
using System.Threading;
namespace 插件
{
    [Autodesk.Revit.Attributes.Transaction(TransactionMode.Manual)]
    [Autodesk.Revit.Attributes.Regeneration(RegenerationOption.Manual)]
    [Autodesk.Revit.Attributes.Journaling(JournalingMode.UsingCommandData)]
    public class Command : IExternalCommand
    {
        public readonly double unit = 304.8;

        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elementSet)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document doc = uidoc.Document;
            Selection selection = uidoc.Selection;
            IList<Reference> reffs = selection.PickObjects(ObjectType.Element);
            string info = string.Empty;
            foreach(var item in reffs)
            {
                info += doc.GetElement(item).Name + "\n";
            }
            info += "点击确认三秒钟以后会自动取消选中地元素";
            TaskDialog.Show("Title", info);
            Thread.Sleep(3 * 1000);
            // 方法1
            elementSet.Clear();
            // 方法2
            selection.SetElementIds(new List<ElementId>());
            return Result.Succeeded;
        }
    }
}

8.选中元素

2015以后的版本都用selection.SetElementIds(List ids)这个方法来设置元素选中。

using System;
using System.Collections.Generic;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.UI.Selection;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.DB.Electrical;
using System.Threading;
namespace 插件
{
    [Autodesk.Revit.Attributes.Transaction(TransactionMode.Manual)]
    [Autodesk.Revit.Attributes.Regeneration(RegenerationOption.Manual)]
    [Autodesk.Revit.Attributes.Journaling(JournalingMode.UsingCommandData)]
    public class Command : IExternalCommand
    {
        public readonly double unit = 304.8;

        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elementSet)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document doc = uidoc.Document;
            Selection selection = uidoc.Selection;
            Reference reff = selection.PickObject(ObjectType.Element);
            Element elem = doc.GetElement(reff);
            selection.SetElementIds(new List<ElementId>() { elem.Id});
            TaskDialog.Show("选择", "已经选中");
            Thread.Sleep(2*1000);
            // 传入一个空的列表,即取消选中
            selection.SetElementIds(new List<ElementId>());
            return Result.Succeeded;
        }
    }
}

9获取元素的几何信息

Revit中元素的几何信息可以通过get_Geometry(Options)方法获取,这个方法返回一个GeometryElement类型的值,GeometryElement里面包含了这个元素所有的GeometryObject
这个函数需要传入一个Options的参数,Options有一个默认无参数的构造器,Options类有下面几个属性可以设置:

属性 说明
ComputeReferences 这是一个布尔值,如果是true,那么返回的Reference不为空,默认为false
IncludeNonVisibleObjects 设置是否包含不可见的几何
DetailLevel 对应视图的详细程度
IsReadOnly 是否只读
View 返回这个视图中可见的几何
注意:获取元素几何信息一般分为系统族和载入族来考虑,如果是系统族使用XX.get_Geometry(opt)获取到的就是实体(Solid)
  • 如果族是载入族,要看是否是剪切过的族,如果是剪切过的族,那么方法与系统族类似
  • 如果不是剪切过的族,那么
  1. 通过XX.get_Geometry(opt)获取到GeometryElement
  2. 再从GeometryElement获取到GeometryInstance,再从GeometryInstance.GetInstanceGeometr()或者GeometryInstance.GetSymbolGeometry()获取Solid进行操作

GeometryObject有下面的几个子类:

  • Autodesk.Revit.DB.XX.Curve
  • Autodesk.Revit.DB.XX.Face
  • Autodesk.Revit.Db.XX.Edge
  • Autodesk.Revit.DB.XX.GeometryElement
  • Autodek.Revit.DB.XX.GeometryInstance
  • Autodesk.Revit.DB.XX.Mesh
  • Autodesk.Revit.DB.XX.Point
  • Autodesk.Revit.DB.XX.PolyLine
  • Autodesk.Revit.DB.XX.Profile
  • Autodesk.Revit.DB.XX.Solid
下面的代码实现了获取一个系统族(墙)的底面积和一个载入族(柱子)的底面积 ```csharp using System; using System.Collections.Generic; using Autodesk.Revit.UI; using Autodesk.Revit.DB; using Autodesk.Revit.Attributes; using Autodesk.Revit.UI.Selection; using Autodesk.Revit.DB.Mechanical; using Autodesk.Revit.DB.Plumbing; using Autodesk.Revit.DB.Electrical; using System.Threading; namespace 插件 { [Autodesk.Revit.Attributes.Transaction(TransactionMode.Manual)] [Autodesk.Revit.Attributes.Regeneration(RegenerationOption.Manual)] [Autodesk.Revit.Attributes.Journaling(JournalingMode.UsingCommandData)] public class Command : IExternalCommand { public readonly double unit = 304.8;
    public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elementSet)
    {
        UIDocument uidoc = commandData.Application.ActiveUIDocument;
        Document doc = uidoc.Document;
        Selection selection = uidoc.Selection;

        Options opt = new Options
        {
            ComputeReferences = true,
            DetailLevel = ViewDetailLevel.Fine,
            IncludeNonVisibleObjects = false
        };
        // wall
        Reference reff = selection.PickObject(ObjectType.Element, "选择一堵墙");
        Wall wall = doc.GetElement(reff) as Wall;
        GetWallBottomFaceAndComputeArea(wall, opt);

        // column
        Reference refColumn = selection.PickObject(ObjectType.Element, "请选择一个柱子");
        FamilyInstance instance = doc.GetElement(refColumn) as FamilyInstance;
        GetColumnBottomFaceAndComputeArea(instance, opt);



        return Result.Succeeded;
    }
    /// 
    /// 获取一个没有剪切的柱子实体最下面的面,并且输出面积
    /// 
    /// 
    /// 
    public void GetColumnBottomFaceAndComputeArea(FamilyInstance fmInstance,Options opt)
    {
        GeometryElement geoElem = fmInstance.get_Geometry(opt);
        Face face = null;
        foreach(GeometryObject obj in geoElem)
        {
            if(obj is Solid)
            {
                Solid solid = obj as Solid;
                if(solid.Faces.Size>0)
                {
                face = FindBottomFace(solid);
                }
            }
            else if(obj is GeometryInstance)
            {
                GeometryInstance gmInstance = obj as GeometryInstance;
                // 获取实例的solid
                GeometryElement geoElem1 = gmInstance.GetInstanceGeometry();
                // 获取族类型的solid
                //GeometryElement geoElem1 = gmInstance.GetSymbolGeometry();
                foreach(GeometryObject obj2 in geoElem1)
                {
                    if(obj2 is Solid)
                    {
                        Solid solid = obj2 as Solid;
                        if(solid.Faces.Size>0)
                        {
                        face = FindBottomFace(solid);
                        }
                    }
                }
            }
        }
        TaskDialog.Show("柱子的底面积", face.Area.ToString());
    }
    /// 
    /// 获取墙体实体最下面的面,并且输出面积
    /// 
    /// 
    /// 
    public void GetWallBottomFaceAndComputeArea(Wall wall,Options opt)
    {
        GeometryElement geoElem = wall.get_Geometry(opt);
        foreach(GeometryObject obj in geoElem)
        {
            Solid solid = obj as Solid;
            // 排除获取到的不是实体和获取到的无效实体
            if(solid!=null && solid.Faces.Size>0)
            {
                Face face = FindBottomFace(solid);
                TaskDialog.Show("面积", face.Area.ToString());
            }
        }
    }
    /// 
    /// 找出一个实体最下面的一个面
    /// 
    /// 
    /// 
    public Face FindBottomFace(Solid solid)
    {
        foreach(Face face in solid.Faces)
        {
            PlanarFace face1 = face as PlanarFace;
            if(face!=null)
            {
                if(face1.FaceNormal.X<0.01 && face1.FaceNormal.Y<0.01 && face1.FaceNormal.Z<0)
                {
                    return face;
                }
            }
        }
        return null;
    }
}   

}

### 10绑定命令——传递创建门命令
```csharp
using System;
using System.Collections.Generic;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.UI.Selection;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.DB.Electrical;
using System.Threading;
namespace 插件
{
    [Autodesk.Revit.Attributes.Transaction(TransactionMode.Manual)]
    [Autodesk.Revit.Attributes.Regeneration(RegenerationOption.Manual)]
    [Autodesk.Revit.Attributes.Journaling(JournalingMode.UsingCommandData)]
    public class Command : IExternalCommand
    {
        public readonly double unit = 304.8;

        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elementSet)
        {
            UIApplication uiapp = new UIApplication(commandData.Application.Application);
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document doc = uidoc.Document;
            Selection selection = uidoc.Selection;
            // 传递创建门的命令
            CommandTest(uiapp);



            return Result.Succeeded;
        }

        private void CommandTest(UIApplication uiapp)
        {
            RevitCommandId CommandId = RevitCommandId.LookupPostableCommandId(PostableCommand.Door);
            if(uiapp.CanPostCommand(CommandId))
            {
                uiapp.PostCommand(CommandId);
            }
        }


    }
}

10 预览Revit视图的控件

Command类

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.Attributes;
namespace 插件2
{
    [Autodesk.Revit.Attributes.Transaction(TransactionMode.Manual)]
    [Autodesk.Revit.Attributes.Regeneration(RegenerationOption.Manual)]
    [Autodesk.Revit.Attributes.Journaling(JournalingMode.UsingCommandData)]
    class Command:IExternalCommand
    {
        public Result Execute(ExternalCommandData commandData,ref string message,ElementSet elementSet)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document doc = uidoc.Document;
            PreWindow window = new PreWindow(commandData.Application.Application);
            window.Show();
           return Result.Succeeded;
        }
    }
}

界面的XMAL

<Window x:Class="插件2.PreWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:插件2"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="400">
    <Grid Name="grid">
        
    Grid>
Window>

界面后台

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
namespace 插件2
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    public partial class PreWindow : Window
    {
        UIApplication uiapp = null;
        Autodesk.Revit.ApplicationServices.Application app = null;
        Document doc = null;
        public PreWindow()
        {
            InitializeComponent();
        }
        public PreWindow(Autodesk.Revit.ApplicationServices.Application app)
        {
            InitializeComponent();
            this.app = app;
            uiapp = new UIApplication(this.app);
            this.doc = uiapp.ActiveUIDocument.Document;
            PreviewControl preview = new PreviewControl(doc, doc.ActiveView.Id);
            this.grid.Children.Add(preview);
        }

    }
}

效果如下:

Revit开发小功能集合_第1张图片

11 对元素的基本操作

Revit中可以通过API对元素进行复制,移动,旋转,镜像等基本操作。这些功能都可以通过ElementTransformUtils类来实现,下面是简单的示例

using System;
using System.Collections.Generic;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.UI.Selection;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.DB.Electrical;
using System.Threading;
namespace 插件
{
    [Autodesk.Revit.Attributes.Transaction(TransactionMode.Manual)]
    [Autodesk.Revit.Attributes.Regeneration(RegenerationOption.Manual)]
    [Autodesk.Revit.Attributes.Journaling(JournalingMode.UsingCommandData)]
    public class Command : IExternalCommand
    {
        public readonly double unit = 304.8;

        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elementSet)
        {
            UIApplication uiapp = new UIApplication(commandData.Application.Application);
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document doc = uidoc.Document;
            Selection selection = uidoc.Selection;

            #region 移动
            TaskDialog.Show("Move", "下面请选择一个墙体,这个墙体将会向右移动1000mm");
            Wall wall = doc.GetElement(selection.PickObject(ObjectType.Element)) as Wall;
            using (Transaction ts = new Transaction(doc, "Move"))
            {
                ts.Start();
                ElementTransformUtils.MoveElement(doc, wall.Id, new XYZ(1000 / unit, 0, 0));
                ts.Commit();
            }
            #endregion

            #region 复制
            TaskDialog.Show("Copy", "选择一个墙体,这个墙体上方1000mm处复制一个新的墙体");
            Wall wall1 = doc.GetElement(selection.PickObject(ObjectType.Element)) as Wall;
            using (Transaction ts = new Transaction(doc, "Copy"))
            {
                ts.Start();
                ElementTransformUtils.CopyElement(doc, wall1.Id, new XYZ(0, 1000 / 304.8, 0));
                ts.Commit();
            }
            #endregion

            #region 旋转
            TaskDialog.Show("Rotate", "选择一个墙体,将会把这个墙体顺时针旋转45度");
            Wall wall2 = doc.GetElement(selection.PickObject(ObjectType.Element)) as Wall;
            using (Transaction ts = new Transaction(doc, "Rotate"))
            {
                ts.Start();
                XYZ pt1 = ((wall2.Location as LocationCurve).Curve as Line).GetEndPoint(0);
                Line line = Line.CreateBound(new XYZ(pt1.X, pt1.Y, 0), pt1);
                ElementTransformUtils.RotateElement(doc, wall2.Id, line, 45);
                ts.Commit();
            }
            #endregion


            #region 镜像
            TaskDialog.Show("Mirror", "选择一个墙体,再点击两个点,将会把这个墙体以两个点连成的直线为轴镜像一个新的墙体");
            Wall wall3 = doc.GetElement(selection.PickObject(ObjectType.Element)) as Wall;
            using (Transaction ts = new Transaction(doc, "Mirror"))
            {
                ts.Start();
                XYZ pt1 = selection.PickPoint("请选择镜像轴的第一个端点");
                XYZ pt2 = selection.PickPoint("请选择镜像轴的第二个端点");
                XYZ origin = (pt1 + pt2)/2;
                XYZ pt3 = new XYZ(origin.X, origin.Y, origin.Z + 100);
                Plane plane = Plane.CreateByThreePoints(pt1, pt2, pt3);
                ElementTransformUtils.MirrorElement(doc, wall3.Id, plane);
                ts.Commit();
            }
            #endregion




            return Result.Succeeded;
        }



    }
}

持续更新

参考博客

你可能感兴趣的:(Revit项目篇)