RevitAPI: How to get mirrored result after calling ElementTransformUtils.MirrorElement

By Aaron Lu

中文链接

In current Revit (2015 and before), there are 2 methods to mirror elements, they are:

ElementTransformUtils.MirrorElement and

ElementTransformUtils.MirrorElements

But the problem is they don’t have return value, meaning we can get the mirrored element(s) directly.

However, there is a workaround to accomplish that using Application.DocumentChanged event.

Workflow:

  1. Subscribe Application.DocumentChanged event
  2. Mirror element(s)
  3. event raises, in the event handler, get the added new element(s)

Example Code, please note the DocumentChanged event can only be raised after the transaction is committed.

public static ICollection<ElementId> MirrorElement(
Document doc, ElementId elementId, Plane plane)
{
if (doc == null || plane == null ||
elementId == ElementId.InvalidElementId ||
!ElementTransformUtils.CanMirrorElement(doc, elementId))
throw new ArgumentException("Argument invalid");
ICollection<ElementId> result = new List<ElementId>();
// create DocumentChanged event handler
var documentChangedHandler =
new EventHandler<DocumentChangedEventArgs>(
(sender, args) => result = args.GetAddedElementIds());
// subscribe the event
doc.Application.DocumentChanged += documentChangedHandler;
using (Transaction transaction = new Transaction(doc))
{
try
{
transaction.Start("Mirror");
ElementTransformUtils.MirrorElement(
doc, elementId, plane);
transaction.Commit();
}
catch (Exception ex)
{
TaskDialog.Show("ERROR", ex.ToString());
transaction.RollBack();
}
finally
{
// unsubscribe the event
doc.Application.DocumentChanged -= documentChangedHandler;
}
}
return result;
}

How to use this function

(Following code is to mirror a FamilyInstance near itself, and then display the id(s) of the mirrored elements)

var instance = RevitDoc.GetElement(elementId) as FamilyInstance;
if (instance != null)
{
var transform = instance.GetTransform();
var mirrored = MirrorElement(RevitDoc, instance.Id,
new Plane(transform.BasisX, transform.Origin));
TaskDialog.Show("Info", "Mirror succeeded! New mirrored ids: "
+ mirrored.Aggregate("", (ss, id) => ss + id + " "));
}

Comments

Leave a Reply

Discover more from Autodesk Developer Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading