Scale a Graphic

R

rpond

I want to print the contents of a Component. The problem is that if
the size of the component is greater than the size of the page, it does
not print the whole component. I want to be able to scale down the
Graphic in the print() function so that it fits the page. I plan to
use the Graphic2d.scale() method. How can I get the page size to
determine the correct scale?

Thanks.
 
A

Alex Hunsley

rpond said:
I want to print the contents of a Component. The problem is that if
the size of the component is greater than the size of the page, it does
not print the whole component. I want to be able to scale down the
Graphic in the print() function so that it fits the page. I plan to
use the Graphic2d.scale() method. How can I get the page size to
determine the correct scale?

To get the size of a (realised) JComponent, then call getSize() on it.
It will return a Dimension containing pixel size, let us call that d1.
Now suppose the dimension (in pixels) of your screen or display area
(printout) is d2.

Now, I'm assuming you want conservative scaling, i.e. you can see all of
the component on the screen, and you wish to maintain the aspect ratio...

Work out the width/height ratio of the two dimensions:

r1 = (float)d1.getWidth()/(float)d1.getHeight();
r2 = (float)d2.getWidth()/(float)d2.getHeight();

Now you examine these two ratios to decide whether to scale your graphic
to fit on the X or the Y scale:

float scaleFactor = 1;
if (r1 > r2) {
// we need to scale by the width of the
// component, as it is proportionally wider/fatter than
// the screen area
scaleFactor = (float)d2.getWidth() / (float)d1.getWidth();
}
else {
// we need to scale by the height of the
// component, as it is proportionally taller than
// the screen area
scaleFactor = (float)d2.getHeight() / (float)d1.getHeight();
}

Then set the scaleFactor on the Graphics2D object before rendering:

g2d.setScale(scaleFactor, scaleFactor);


I've not actually tested this code, but you get the idea...
alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top