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

Recommended Answers

All 2 Replies

...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

commented: Thanks for the tips :) +1

Thanks Ezzaral :) Will try this out and repost if I still have probs.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.