70002583 How can I calculate the Bounding Box of entities in a specific view

Article 70002583
Type HowTo
Product Engine
Version 11
Date Added 10/29/2024 12:00:00 AM
Fixed 11.3.1.0 (10/29/2024 12:00:00 AM)
Submitted by Peter Chanios

Summary

How can I calculate the Bounding Box of entities in a specific view

Solution

In order to calculate the Bounding Box of entities in a specific view (usually this requirement is for 3D objects) we will use a custom render that we have like below

BoundingBoxRender render = new BoundingBoxRender(1.0);
render.StartDraw(true);
if (render.Started)
{
      render.PushMatrix(doc.World2ViewMatrix);
      foreach (vdFigure fig in doc.ActiveLayOut.Entities) fig.Draw(render);
      render.PopMatrix();
      render.EndDraw();
}
Box viewBox = render.BoundigBox;

//Perform a zoom in order to see the result.        
doc.ZoomWindow(viewBox.Min, viewBox.Max);

And then we can add a rect or a polyline with Thickness in order to see the calculated Bounding Box

//Create a vdrect just to see the result
vdRect rc = new vdRect(doc, viewBox.Min, viewBox.Width, viewBox.Height, 0);
rc.Thickness = viewBox.Thickness;
rc.PenColor = new vdColor(Color.Red);
rc.LineWeight = VdConstLineWeight.LW_200;
rc.Transformby(doc.View2WorldMatrix);
doc.Model.Entities.AddItem(rc);
                
//Or a polyline
gPoints points1 = viewBox.TogPoints();
foreach (gPoint pt in points1) pt.z = viewBox.ZMin;
vdPolyline pl = new vdPolyline(doc,points1);
pl.Thickness = viewBox.Thickness;
pl.PenColor = new vdColor(Color.Green);
pl.LineWeight = VdConstLineWeight.LW_100;
pl.Transformby(doc.View2WorldMatrix);
doc.Model.Entities.AddItem(pl);
doc.Redraw(true);

Also we can export a bitmap that will only show these entities (without any gap around like below.
Check the comments to understand the way the size of the bitmap in pixels is calculated

//Filename
doc.ActiveLayOut.Printer.PrinterName = @"C:\test.jpg";

//The following two properties define the size of the bitmap
doc.ActiveLayOut.Printer.Resolution = 200;
//We calculate the Height in reference of the specific width of 827 and we round it to the upper bound so we do not loose any pixel rounding the double into an integer.
int viewheight =  (int)(Math.Ceiling (827 * (viewBox.Height / viewBox.Width)));
doc.ActiveLayOut.Printer.paperSize = new Rectangle(0, 0, 827, viewheight);
//For example we set a width of 827 which is 8,27 inches , the size of the A4 paper
// With resolution 200 the width of the bitmap will be 8,27 * 200 = 1654 pixels
// the height will be calculated above depending the size of the entities that we have in our drawing

//Important is to set the PrintWindow. Do not use any Extends or ScaleToFit because these methods will change the calculated view
doc.ActiveLayOut.Printer.PrintWindow = viewBox;
//Background color
doc.ActiveLayOut.Printer.UseDefaultPrinterBkColor = true;
//Export
doc.ActiveLayOut.Printer.Update();
doc.ActiveLayOut.Printer.PrintOut();

Send comments on this topic.