0

Hi all,

I am wanting to display an image that is aligned so that the centre of a string of text is in line with the centre of the image. I know the image's dimensions and the length of the string, as well as the font I am using to draw the text, but I can't work out how to calculate the coordinates of the centre of the string. I am using the java.awt.Graphics.drawString and drawImage methods to draw each part of my object. If I have set my graphics component's font to have a size of 12 say, does this mean that each character takes up 12 x 12 pixels?

Thanks in advance for any suggestions,
darkagn

2
Contributors
2
Replies
4
Views
9 Years
Discussion Span
Last Post by darkagn
1

...I am using the java.awt.Graphics.drawString and drawImage methods to draw each part of my object. If I have set my graphics component's font to have a size of 12 say, does this mean that each character takes up 12 x 12 pixels?

No, it's a little more complicated than that, but still easily available. You'll need to call Graphics.getFontMetrics() to obtain the font metrics for the current font. FontMetrics provides methods for obtaining dimensions of a particular string for that font and graphics context, such as getHeight() and stringWidth(java.lang.String). That should be all you need to center up any given string on your image.

Edit: You can find more detailed info on FontMetrics and handling text in the graphics context if you need it in the 2D graphics tutorial: http://java.sun.com/docs/books/tutorial/2d/text/measuringtext.html

Votes + Comments
Thanks for the tips :)
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.