Sven Mielordt wrote:
Hi fellows,
I have a short question concerning drawString() on Graphics2D.
When using it, the string is printed horizontally.
But how can I print text vertically or at arbitrary angles???
A refining question concerns the number of pixels needed for the string.
Is there any method to find out how many pixels in all directions will be
occupied?
Thank you,
Sven
_____________________________________________________________
Here is a utility method that I use for JFreeChart - it seems to work
pretty well:
/**
* A utility method for drawing rotated text.
* <P>
* A common rotation is -Math.PI/2 which draws text 'vertically'
(with the
* top of the characters on the left).
*
* @param text the text.
* @param g2 the graphics device.
* @param textX the x-coordinate for the text (before rotation).
* @param textY the y-coordinate for the text (before rotation).
* @param angle the angle of the (clockwise) rotation (in radians).
* @param rotateX the point about which the text is rotated.
* @param rotateY the point about which the text is rotated.
*/
public static void drawRotatedString(final String text,
final Graphics2D g2,
final float textX,
final float textY,
final double angle,
final float rotateX,
final float rotateY) {
if ((text == null) || (text.equals(""))) {
return;
}
final AffineTransform saved = g2.getTransform();
// apply the rotation...
final AffineTransform rotate = AffineTransform.getRotateInstance(
angle, rotateX, rotateY
);
g2.transform(rotate);
if (useDrawRotatedStringWorkaround) {
// workaround for JDC bug ID 4312117 and others...
final TextLayout tl = new TextLayout(
text, g2.getFont(), g2.getFontRenderContext()
);
tl.draw(g2, textX, textY);
}
else {
// replaces this code...
g2.drawString(text, textX, textY);
}
g2.setTransform(saved);
}
A couple of comments on the code:
(1) the method allows you to specify the text anchor point and the
rotation point separately - that is used in our library to provide a
range of different alignment options. Just pass in the same (x, y)
point for the rotation point for the simplest case.
(2) the 'useDrawRotatedStringWorkaround' flag just gives two different
ways to draw the text, as a workaround for some JDK bugs (probably fixed
now, I don't get so many reports about the problem anymore). I know
that one method failed on some platforms and the other method failed on
some other platforms, but I forget which.
Regards,
Dave Gilbert
JFreeChart Project Leader
===========================================================================
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff JAVA2D-INTEREST". For general help, send email to
[EMAIL PROTECTED] and include in the body of the message "help".