主题:创建空间和分区。

总结:

这个示例演示了三个主要特点:

1. 如何获取指定标高中的所有空间元素。

2. 如何获取指定标高中的所有区域元素。

3. 如何为每个封闭的墙体环或封闭的空间分隔创建空间元素。

4. 如何在指定的层级和阶段中创建新的区域元素。

5. 如何在区域元素中添加/删除空间元素。

相关类:

Autodesk.Revit.UI.IExternalCommand

Autodesk.Revit.DB.Mechanical.Space

Autodesk.Revit.DB.Mechanical.Zone

Autodesk.Revit.DB.Phase

Autodesk.Revit.Creation.Document

项目文件:

Command.cs此文件包含类“Command”,该类继承自“IExternalCommand”接口并实现“Execute”方法。

DataManager.cs它包含一个名为“DataManager”的类,用于获取、创建或编辑Space元素和Zone元素。

SpaceManager.cs它包含一个名为“SpaceManager”的类,用于管理当前文档中的Space元素。它可以为每个闭合的墙循环或闭合的空间分隔创建空间元素。

ZoneManager.cs它包含一个名为“ZoneManager”的类,用于管理当前文档中的Zone元素。它可以在Zone元素中添加/删除空间。

功能:

-获取活动文档中的所有Space元素和Zone元素,并按级别分组列出它们。

-为指定标高中的每个闭合墙循环或闭合空间分隔创建空间元素。

-在指定的标高和阶段中创建一个新的Zone元素。

-在Zone元素中添加/删除空间

实施:

-使用元素过滤器来获取所有的Space和Zone元素。

-通过ElementSet NewSpaces(标高、阶段、视图视图)方法为每个闭合墙循环或闭合空间分隔创建空间。

-通过ElementSet NewSpaces(标高、阶段、视图视图)方法为每个闭合墙循环或闭合空间分隔创

完整的源代码请加入QQ群649037449,在群文件中下载RevitSDK.exe,解压后在文件夹中搜索本文中应用程序名称即可获得完整源码

DataManager.cs

//
// (C) Copyright 2003-2019 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
// 

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB.Mechanical;

namespace Revit.SDK.Samples.AddSpaceAndZone.CS
{
    /// <summary>
    /// The DataManager Class is used to obtain, create or edit the Space elements and Zone elements.
    /// </summary>
    public class DataManager
    {
        ExternalCommandData m_commandData;
        List<Level>  m_levels;
        SpaceManager m_spaceManager;
        ZoneManager m_zoneManager;
        Level m_currentLevel;
        Phase m_defaultPhase;

        /// <summary>
        /// The constructor of DataManager class.
        /// </summary>
        /// <param name="commandData">The ExternalCommandData</param>
        public DataManager(ExternalCommandData commandData)
        {
            m_commandData = commandData;
            m_levels = new List<Level>();
            Initialize();
            m_currentLevel = m_levels[0];
            Parameter para = commandData.Application.ActiveUIDocument.Document.ActiveView.get_Parameter(Autodesk.Revit.DB.BuiltInParameter.VIEW_PHASE);
            Autodesk.Revit.DB.ElementId phaseId = para.AsElementId();
            m_defaultPhase = commandData.Application.ActiveUIDocument.Document.GetElement(phaseId) as Phase;
        }

        /// <summary>
        /// Initialize the data member, obtain the Space and Zone elements.
        /// </summary>
        private void Initialize()
        {
            Dictionary<int, List<Space>> spaceDictionary = new Dictionary<int, List<Space>>();
            Dictionary<int, List<Zone>> zoneDictionary = new Dictionary<int, List<Zone>>();

            Document activeDoc = m_commandData.Application.ActiveUIDocument.Document;

            FilteredElementIterator levelsIterator = (new FilteredElementCollector(activeDoc)).OfClass(typeof(Level)).GetElementIterator();
            FilteredElementIterator spacesIterator =(new FilteredElementCollector(activeDoc)).WherePasses(new SpaceFilter()).GetElementIterator();
            FilteredElementIterator zonesIterator = (new FilteredElementCollector(activeDoc)).OfClass(typeof(Zone)).GetElementIterator();
          
            levelsIterator.Reset();
            while (levelsIterator.MoveNext())
            {
                Level level = levelsIterator.Current as Level;
                if (level != null)
                {
                    m_levels.Add(level);
                    spaceDictionary.Add(level.Id.IntegerValue, new List<Space>());
                    zoneDictionary.Add(level.Id.IntegerValue, new List<Zone>());
                }
            }

            spacesIterator.Reset();
            while (spacesIterator.MoveNext())
            {
                Space space = spacesIterator.Current as Space;
                if (space != null)
                {
                    spaceDictionary[space.LevelId.IntegerValue].Add(space);
                }
            }

            zonesIterator.Reset();
            while (zonesIterator.MoveNext())
            {
                Zone zone = zonesIterator.Current as Zone;
                if (zone != null && activeDoc.GetElement(zone.LevelId) != null)
                {
                    zoneDictionary[zone.LevelId.IntegerValue].Add(zone);
                }
            }

            m_spaceManager = new SpaceManager(m_commandData, spaceDictionary);
            m_zoneManager = new ZoneManager(m_commandData, zoneDictionary);
        }

        /// <summary>
        /// Get the Level elements.
        /// </summary>
        public ReadOnlyCollection<Level> Levels
        {
            get
            {
                return new ReadOnlyCollection<Level>(m_levels);
            }
        }

        /// <summary>
        /// Create a Zone element.创建区域的函数
        /// </summary>
        public void CreateZone()
        {
            if (m_defaultPhase == null)
            {
                Autodesk.Revit.UI.TaskDialog.Show("Revit", "The phase of the active view is null, you can't create zone in a null phase");
                return;
            }
            try
            {
                this.m_zoneManager.CreateZone(m_currentLevel, m_defaultPhase);
            }
            catch (Exception ex)
            {
                Autodesk.Revit.UI.TaskDialog.Show("Revit", ex.Message);
            }         
        }

        /// <summary>
        /// Create some spaces.
        /// </summary>
        public void CreateSpaces()
        {           
            if (m_defaultPhase == null)
            {
                Autodesk.Revit.UI.TaskDialog.Show("Revit", "The phase of the active view is null, you can't create spaces in a null phase");
                return;
            }

            try
            {
                if (m_commandData.Application.ActiveUIDocument.Document.ActiveView.ViewType == Autodesk.Revit.DB.ViewType.FloorPlan)
                {
                    m_spaceManager.CreateSpaces(m_currentLevel, m_defaultPhase);
                }
                else
                {
                    Autodesk.Revit.UI.TaskDialog.Show("Revit", "You can not create spaces in this plan view");
                }
            }
            catch (Exception ex)
            {
                Autodesk.Revit.UI.TaskDialog.Show("Revit", ex.Message);
            }               
        }

        /// <summary>
        /// Get the Space elements.
        /// </summary>
        /// <returns>A space list in current level.</returns>
        public List<Space> GetSpaces()
        {
            return m_spaceManager.GetSpaces(m_currentLevel);
        }

        /// <summary>
        /// Get the Zone elements.
        /// </summary>
        /// <returns>A Zone list in current level.</returns>
        public List<Zone> GetZones()
        {
            return m_zoneManager.GetZones(m_currentLevel);
        }

        /// <summary>
        /// Update the current level.
        /// </summary>
        /// <param name="level"></param>
        public void Update(Level level)
        {
            this.m_currentLevel = level;
        }
    }
}

SpaceManager.cs

//
// (C) Copyright 2003-2019 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
// 

using System;
using System.Collections.Generic;
using System.Text;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB.Mechanical;

namespace Revit.SDK.Samples.AddSpaceAndZone.CS
{
    /// <summary>
    /// The ZoneManager class is used to manage the Zone elements in the current document.
    /// </summary>
    class ZoneManager
    {
        ExternalCommandData m_commandData;
        Dictionary<int, List<Zone>> m_zoneDictionary;
        Level m_currentLevel;
        Zone m_currentZone;

        /// <summary>
        /// The constructor of ZoneManager class.
        /// </summary>
        /// <param name="commandData">The ExternalCommandData</param>
        /// <param name="zoneData">The spaceData contains all the Zone elements in different level.</param>
        public ZoneManager(ExternalCommandData commandData, Dictionary<int, List<Zone>>  zoneData)
        {
            m_commandData = commandData;
            m_zoneDictionary = zoneData;
        }

        /// <summary>
        /// Create a zone in a specified level and phase.
        /// </summary>
        /// <param name="level"></param>
        /// <param name="phase"></param>
        public void CreateZone(Level level, Phase phase)
        {
            Zone zone = m_commandData.Application.ActiveUIDocument.Document.Create.NewZone(level, phase);
            if (zone != null)
            {
                this.m_zoneDictionary[level.Id.IntegerValue].Add(zone);
            }
        }

        /// <summary>
        /// Add some spaces to current Zone.
        /// </summary>
        /// <param name="spaces"></param>
        public void AddSpaces(SpaceSet spaces)
        {
            m_currentZone.AddSpaces(spaces);
        }

        /// <summary>
        /// Remove some spaces to current Zone.
        /// </summary>
        /// <param name="spaces"></param>
        public void RemoveSpaces(SpaceSet spaces)
        {
            m_currentZone.RemoveSpaces(spaces);
        }
      
        /// <summary>
        /// Get the Zone elements in a specified level.
        /// </summary>
        /// <param name="level"></param>
        /// <returns>Return a zone list</returns>
        public List<Zone> GetZones(Level level)
        {
            m_currentLevel = level;
            return m_zoneDictionary[level.Id.IntegerValue];
        }

        /// <summary>
        /// Get/Set the Current Zone element.
        /// </summary>
        public Zone CurrentZone
        {
            get
            {
                return CurrentZone;
            }
            set
            {
                m_currentZone = value;
            }
        }
    }
}

ZoneManager.cs

//
// (C) Copyright 2003-2019 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
// 

using System;
using System.Collections.Generic;
using System.Text;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;

using Autodesk.Revit.DB.Mechanical;

namespace Revit.SDK.Samples.AddSpaceAndZone.CS
{
    /// <summary>
    /// The SpaceManager class is used to manage the Spaces elements in the current document.
    /// </summary>
    class SpaceManager
    {
        ExternalCommandData m_commandData;
        Dictionary<int, List<Space>> m_spaceDictionary;

        /// <summary>
        /// The constructor of SpaceManager class.
        /// </summary>
        /// <param name="data">The ExternalCommandData</param>
        /// <param name="spaceData">The spaceData contains all the Space elements in different level.</param>
        public SpaceManager(ExternalCommandData data, Dictionary<int,List<Space>> spaceData)
        {
            m_commandData = data;
            m_spaceDictionary = spaceData;
        }

        /// <summary>
        /// Get the Spaces elements in a specified level.
        /// </summary>
        /// <param name="level"></param>
        /// <returns>Return a space list</returns>
        public List<Space> GetSpaces(Level level)
        {
            return m_spaceDictionary[level.Id.IntegerValue];
        }

        /// <summary>
        /// Create the space for each closed wall loop or closed space separation in the active view.
        /// </summary>
        /// <param name="level">The level in which the spaces is to exist.</param>
        /// <param name="phase">The phase in which the spaces is to exist.</param>
        public void CreateSpaces(Level level, Phase phase)
        {
            try
            {
                ICollection<ElementId> elements = m_commandData.Application.ActiveUIDocument.Document.Create.NewSpaces2(level, phase, this.m_commandData.Application.ActiveUIDocument.Document.ActiveView);
                foreach (ElementId elem in elements)
                {
                    Space space = m_commandData.Application.ActiveUIDocument.Document.GetElement(elem) as Space;
                    if (space != null)
                    {
                        m_spaceDictionary[level.Id.IntegerValue].Add(space);
                    }
                }
                if (elements == null || elements.Count == 0)
                {
                    Autodesk.Revit.UI.TaskDialog.Show("Revit", "There is no enclosed loop in " + level.Name);
                }
                 
            }
            catch (Exception ex)
            {
                Autodesk.Revit.UI.TaskDialog.Show("Revit", ex.Message);
            }
        }
    }
}

Command2.vb

' 
' (C) Copyright 2003-2019 by Autodesk, Inc.
' 
' Permission to use, copy, modify, and distribute this software in
' object code form for any purpose and without fee is hereby granted,
' provided that the above copyright notice appears in all copies and
' that both that copyright notice and the limited warranty and
' restricted rights notice below appear in all supporting
' documentation.
'
' AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
' AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
' MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE.  AUTODESK, INC.
' DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
' UNINTERRUPTED OR ERROR FREE.
' 
' Use, duplication, or disclosure by the U.S. Government is subject to
' restrictions set forth in FAR 52.227-19 (Commercial Computer
' Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
' (Rights in Technical Data and Computer Software), as applicable.
'

Option Explicit On
Imports System
Imports Autodesk.Revit.DB

<Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)> _
<Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)> _
<Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)> _
Public Class Command2
    Implements Autodesk.Revit.UI.IExternalCommand

    ''' <summary>
    ''' Implement this method as an external command for Revit.
    ''' </summary>
    ''' <param name="commandData">An object that is passed to the external application 
    ''' which contains data related to the command, 
    ''' such as the application object and active view.</param>
    ''' <param name="message">A message that can be set by the external application 
    ''' which will be displayed if a failure or cancellation is returned by 
    ''' the external command.</param>
    ''' <param name="elements">A set of elements to which the external application 
    ''' can add elements that are to be highlighted in case of failure or cancellation.</param>
    ''' <returns>Return the status of the external command. 
    ''' A result of Succeeded means that the API external method functioned as expected. 
    ''' Cancelled can be used to signify that the user cancelled the external operation 
    ''' at some point. Failure should be returned if the application is unable to proceed with 
    ''' the operation.</returns>
    Public Function Execute(ByVal commandData As Autodesk.Revit.UI.ExternalCommandData, ByRef message As String, _
        ByVal elements As Autodesk.Revit.DB.ElementSet) As Autodesk.Revit.UI.Result _
        Implements Autodesk.Revit.UI.IExternalCommand.Execute

        ' Setup a default message in case any exceptions are thrown that we have not
        ' explicitly handled. On failure the message will be displayed by Revit
        message = "The sample failed"
        Execute = Autodesk.Revit.UI.Result.Failed

        Try
            Dim sharedParameterDefinition As Autodesk.Revit.DB.Definition
            sharedParameterDefinition = commandData.Application.Application.OpenSharedParameterFile.Groups. _
                Item("RevitParameters").Definitions.Item("APIParameter")

            Dim mParameterName As String = sharedParameterDefinition.Name
            Dim mNewParamValue As String = "Hello Revit"

            'get a set of element which is not elementType
            Dim filter As Autodesk.Revit.DB.ElementIsElementTypeFilter
            filter = New Autodesk.Revit.DB.ElementIsElementTypeFilter(True)
            Dim collector As Autodesk.Revit.DB.FilteredElementCollector
            collector = New Autodesk.Revit.DB.FilteredElementCollector(commandData.Application.ActiveUIDocument.Document)
            collector.WherePasses(filter)
            Dim iter As IEnumerator
            iter = collector.GetElementIterator

            Dim transaction As Autodesk.Revit.DB.Transaction
            transaction = New Autodesk.Revit.DB.Transaction(commandData.Application.ActiveUIDocument.Document, "SetParameter")
            transaction.Start()
            Do While (iter.MoveNext)
                Dim element As Autodesk.Revit.DB.Element
                element = iter.Current
                If Not (TypeOf element Is Autodesk.Revit.DB.ElementType) Then
                    If Not (element.Category Is Nothing) Then
                        If (element.Category.Name = "Walls") Then

                            Dim param As Autodesk.Revit.DB.Parameter
                            Dim parameters As Autodesk.Revit.DB.ParameterSet = element.Parameters
                            For Each param In parameters
                                If (param.Definition.Name = mParameterName) Then
                                    Try
                                        param.Set(mNewParamValue)
                                    Catch ex As Exception
                                        Continue For
                                    End Try
                                    Exit For
                                End If
                            Next

                        End If
                    End If
                End If
            Loop
            transaction.Commit()

            ' change our result to successful
            Execute = Autodesk.Revit.UI.Result.Succeeded
            Return Execute
        Catch ex As Exception
            message = ex.Message
            Return Execute
        End Try

    End Function
End Class