translate method in Graphics
I cam across this recently : here
public int print(Graphics g, PageFormat pf, int page) throws
PrinterException {
if (page > 0) { /* We have only one page, and 'page' is zero-based */
return NO_SUCH_PAGE;
}
/* User (0,0) is typically outside the imageable area, so we must
* translate by the X and Y values in the PageFormat to avoid clipping
*/
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY()); // line 2
g.drawString("Hello world!", 100, 100);
/* tell the caller that this page is part of the printed document */
return PAGE_EXISTS;
}
I don't understand the line 2 (commented) in this snippet.(g2d.tra开发者_如何转开发nslate(pf.getImageableX(), pf.getImageableY());)
g2d is a reference of Graphics2d
and translate
is a method found in Graphic class. Then how does it work ?
Edit: The translate method is found in both the Graphics2D class and in the Graphics class since Graphics2D is a child class of Graphics. Being a child of Graphics, it implements all of its methods (including translate), which is why it works.
The translate method in your example is used to move the g2d's origin point to pf's origin point.
Basically, what it does is tell the program to translate (move) every point from g2d to pf's corresponding point.
Let's say g2d starts at (0,0) and pf starts at (100,100), after the translation, g2d's (0,100) point would now be at (100,200), which is pf's (0,100) point since it doesn't start at the same place.
I'm having a hard time making it clear and easy to understand, but if you don't understand what I mean, I'll try explaining it better or just delete the answer altogether and let someone else explain it.
The code looks like it comes from a java.awt.print.Printable
implementation. This is supposed to draw content to a Graphics object which is set to the printer. The translate
call is used if the PageFormat has top/left margins, so the content starts within the printable area of the PageFormat, instead of at 0,0 on the paper, which is not within the printable area.
精彩评论