Revit二次开发--单位转换

Revit内部使用英制单位,我们所熟悉的是公制单位,
因此在在涉及到数据的地方,就要进行单位的转换。
Revit API提供了单位转换类UnitUtils,其中有两个最为常用的方法:

public static double ConvertFromInternalUnits(double value, 	DisplayUnitType displayUnit)//将内部单位转换为某种显示单位,用于获取数值
public static double ConvertToInternalUnits(double value, 	DisplayUnitType displayUnit)//将给定显示单位的值转换为Revit的内部单位,用于设置数值。

其中用到了Parameter的两个属性:DisplayUnitType和StorageType
以下是方法的简单使用:
1)public static double ConvertFromInternalUnits(double value, DisplayUnitType displayUnit)

public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
    {
        UIDocument uiDoc = commandData.Application.ActiveUIDocument;
        Document doc = uiDoc.Document;

        Selection selection = uiDoc.Selection;
        Reference reference = selection.PickObject(ObjectType.Element,"Select a pipe");

        //Pipe pipe = doc.GetElement(reference) as Pipe;
        Duct duct = doc.GetElement(reference) as Duct;
        if (duct != null)
        {
            Parameter paramLength = duct.LookupParameter("长度");
            double paramValue = (double) GetParameterValue(paramLength);
            TaskDialog.Show("ParamValue", paramValue.ToString());
        }
        return Result.Succeeded;
    }

    private object GetParameterValue(Parameter parameter)
    {
        if (parameter.Definition.UnitType != UnitType.UT_Number)
        {
            DisplayUnitType unitype = parameter.DisplayUnitType;
            //TaskDialog.Show("UnitInformation", unitype.ToString());
            StorageType storageType = parameter.StorageType;
            //TaskDialog.Show("StorageType", storageType.ToString());
            switch (storageType)
            {
                case StorageType.Double:
                    return UnitUtils.ConvertFromInternalUnits(parameter.AsDouble(), unitype);
                case StorageType.Integer:
                    return UnitUtils.ConvertFromInternalUnits(parameter.AsInteger(), unitype);
                case StorageType.String:
                    return parameter.AsString();
                case StorageType.ElementId:
                    return parameter.AsElementId();
            }
        }
        return parameter.AsValueString();
    }

2)public static double ConvertToInternalUnits(double value, DisplayUnitType displayUnit)

	 using (Transaction trans = new Transaction(doc))
        {
            trans.Start("Create Level");
            Level level = Level.Create(doc, UnitUtils.ConvertToInternalUnits(3.4 , DisplayUnitType.DUT_METERS));
            level.Name = "标高1";
            trans.Commit();
        }

你可能感兴趣的:(Revit二次开发)