By Joe Ye
It is quite often that Revit users import/link DWG files to Revit views. Some developers has the question how to calculate the coordinates of objects within a linked/imported DWG.
A linked/imported DWG is represented by ImportInstance class. Though the ImportInstance.Geomtry property we can get the objects’ coordinates in the coordinates of the DWG coordinates system, and also the transform of how to convert the objects’ coordinates to the current Revit model coordinates system. So it is straightforward to get the Revit model coordinates. Use the returned transform to convert the DWG internal coordinates to the Revit model coordinates.
Here is the code.
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Autodesk.Revit .DB;
using Autodesk.Revit.UI;
using Autodesk.Revit .ApplicationServices;
using Autodesk.Revit.Attributes ;
using Autodesk.Revit.UI.Selection;
[TransactionAttribute(TransactionMode.Manual)]
public class RevitCommand : IExternalCommand
{
public Result Execute(ExternalCommandData commandData,
ref string messages, ElementSet elements)
{
UIApplication app = commandData.Application;
Document doc = app.ActiveUIDocument.Document;
Autodesk.Revit.UI.Selection.Selection sel = app.ActiveUIDocument.Selection;
Reference ref1 = sel.PickObject(ObjectType.Element, "please pick an import instance");
ImportInstance dwg = doc.GetElement(ref1) as ImportInstance;
if (dwg == null)
return Result.Failed;
Options opt = new Options();
Transform transf = null;
string output = null;
foreach (GeometryObject geoObj in dwg.get_Geometry(opt))
{
if (geoObj is GeometryInstance)
{
GeometryInstance inst = geoObj as GeometryInstance;
transf = inst.Transform;
foreach (GeometryObject geoObj2 in inst.SymbolGeometry)
{
if (geoObj2 is Line)
{
//get the revit model coordinates.
Line l = geoObj2 as Line;
XYZ ptStartInRevit = transf.OfPoint(l.get_EndPoint(0));
XYZ ptEndInRevit = transf.OfPoint(l.get_EndPoint(1));
}
else if (geoObj2 is Arc)
{
Arc a = geoObj2 as Arc;
XYZ ptCenterInRevit = transf.OfPoint(a.Center);
output += "Center = " + ptCenterInRevit.X.ToString()
+ "; " + ptCenterInRevit.Y.ToString() + "; "
+ ptCenterInRevit.Z.ToString() + "\r\n";
}
else
{
// And so on using the same way to convert
// coordinate system of the Revit model.
}
}
}
}
TaskDialog.Show("center of circle/arc", output);
return Result.Succeeded ;
}
}