Java Reference
In-Depth Information
the sketch is scaled to fit the page, and the top-left corner of the sketch stays at the top-left corner of the
printable area on the page and doesn't move to some other point.
Secondly, you want to make sure that you scale x and y by the same factor. If you apply different scales
to the x and y axes in the user coordinate system, the relative proportions of a sketch are not maintained and
circles become ellipses and squares become rectangles.
You can calculate the scale factors you need to apply to get the sketch to fit within the printable area of
the page with the following statements:
// Calculate the x and y scales to fit the sketch to the page
double scaleX = pageFormat.getImageableWidth()/rect.width;
double scaleY = pageFormat.getImageableHeight()/rect.height;
You are using variables of type double for the scale factors here because the getImageableWidth() and
getImageableHeight() methods return values of type double . The scale factor for the x- axis needs to be
such that when you multiply the width of the sketch, rect.width , by the scale factor, the result is no greater
than the width of the printable area on the page, and similarly for scaling the y- axis. Because you want to ap-
ply the same scale to both axes, you should calculate the minimum of the scale factors scaleX and scaleY .
If you then apply this minimum to both axes, the sketch fits within the width and height of the page and is
still in proportion.
TRY IT OUT: Printing the Whole Sketch
You just need to add some code to the print() method in SketcherView to calculate the required scale
factor, and then use the scale() method for the Graphics2D object to apply the scaling transformation:
public int print(Graphics g, // Graphics context for
printing
PageFormat pageFormat, // The page format
int pageIndex) // Index number of current
page
throws PrinterException {
if(pageIndex>0) {
return NO_SUCH_PAGE;
}
Graphics2D g2D = (Graphics2D) g;
// 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);
Search WWH ::




Custom Search