Java Reference
In-Depth Information
// Get sketch bounds
Rectangle rect = theApp.getModel().getModelExtent();
// Calculate the scale to fit sketch to page
double scaleX = pageFormat.getImageableWidth()/rect.width;
double scaleY = pageFormat.getImageableHeight()/rect.height;
// Get minimum scale factor
double scale = Math.min(scaleX, scaleY);
// Move origin to page printing area corner
g2D.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
g2D.scale(scale, scale); // Apply scale factor
g2D.translate(-rect.x, -rect.y); // Move origin to rect top left
paint(g2D); // Draw the sketch
return PAGE _ EXISTS;
}
If you compile and run Sketcher with these changes, you should now be able to print each sketch within
a page.
How It Works
We calculate the scaling factors for each axis as the ratio of the dimension of the printable area on the
page to the corresponding dimension of the rectangle enclosing the sketch. We then take the minimum
of these two scale factors as the scale to be applied to both axes. As long as the scale transformation is
applied after the translation of the coordinate system to the top left corner of the printable page area,
one or other dimension of the sketch will fit exactly within the printable area of the page.
The output is now fine, but if the width of the sketch is greater than the height, we waste a lot of space
on the page. Ideally in this situation we would want to print with a landscape orientation rather than the
default portrait orientation. Let's see what possibilities we have for that.
Printing in Landscape Orientation
We can easily determine when a landscape orientation would be preferable by comparing the width of a
sketch with its height. If the width is larger than the height, a landscape orientation will make better use
of the space on the paper and we will get a larger scale picture.
You can set the orientation in a PageFormat object by calling its setOrientation() method. You
can pass one of three possible argument values, which are defined within the PageFormat class:
Search WWH ::




Custom Search