Hi,
Assuming ids is the selected entities objectId array and ed the current Editor
Here's a 'classical' way.
Using : ZoomObjects(ids)
private void ZoomObjects(ObjectId[] ids)
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
using (Transaction tr = db.TransactionManager.StartTransaction())
using (ViewTableRecord view = ed.GetCurrentView())
{
Matrix3d WCS2DCS =
(Matrix3d.Rotation(-view.ViewTwist, view.ViewDirection, view.Target) *
Matrix3d.Displacement(view.Target - Point3d.Origin) *
Matrix3d.PlaneToWorld(view.ViewDirection))
.Inverse();
Entity ent = (Entity)tr.GetObject(ids[0], OpenMode.ForRead);
Extents3d ext = ent.GeometricExtents;
for (int i = 1; i < ids.Length; i++)
{
ent = (Entity)tr.GetObject(ids[i], OpenMode.ForRead);
ext.AddExtents(ent.GeometricExtents);
}
ext.TransformBy(WCS2DCS);
view.Width = ext.MaxPoint.X - ext.MinPoint.X;
view.Height = ext.MaxPoint.Y - ext.MinPoint.Y;
view.CenterPoint =
new Point2d((ext.MaxPoint.X + ext.MinPoint.X) / 2.0, (ext.MaxPoint.Y + ext.MinPoint.Y) / 2.0);
ed.SetCurrentView(view);
tr.Commit();
}
}
Here's a more generic one using extension methods for the Editor type (others zoom methods can be added to this class, calling or not the Editor.Zoom(Extents3d ext) one).
Using: ed.ZoomObjects(ids) // ids may be any type implementing IEnumerabe<ObjectId>
static class ZoomExtensions
{
// Returns the transformation matrix from the ViewTableRecord DCS to WCS
public static Matrix3d EyeToWorld(this ViewTableRecord view)
{
return
Matrix3d.Rotation(-view.ViewTwist, view.ViewDirection, view.Target) *
Matrix3d.Displacement(view.Target - Point3d.Origin) *
Matrix3d.PlaneToWorld(view.ViewDirection);
}
// Returns the transformation matrix from WCS to the ViewTableRecord DCS
public static Matrix3d WorldToEye(this ViewTableRecord view)
{
return view.EyeToWorld().Inverse();
}
// Process a zoom according to the extents3d in the current viewport
public static void Zoom(this Editor ed, Extents3d ext)
{
using (ViewTableRecord view = ed.GetCurrentView())
{
ext.TransformBy(view.WorldToEye());
view.Width = ext.MaxPoint.X - ext.MinPoint.X;
view.Height = ext.MaxPoint.Y - ext.MinPoint.Y;
view.CenterPoint = new Point2d(
(ext.MaxPoint.X + ext.MinPoint.X) / 2.0,
(ext.MaxPoint.Y + ext.MinPoint.Y) / 2.0);
ed.SetCurrentView(view);
}
}
// Process a zoom objects in the current viewport
public static void ZoomObjects(this Editor ed, IEnumerable<ObjectId> ids)
{
using (Transaction tr = ed.Document.TransactionManager.StartTransaction())
{
Extents3d ext = ids
.Select(id => ((Entity)tr.GetObject(id, OpenMode.ForRead)).GeometricExtents)
.Aggregate((e1, e2) => { e1.AddExtents(e2); return e1; });
ed.Zoom(ext);
tr.Commit();
}
}
}