aspose file tools
The moose likes Swing / AWT / SWT and the fly likes Center text on an image Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Reply Bookmark "Center text on an image" Watch "Center text on an image" New topic
Author

Center text on an image

Kerry Wilson
Ranch Hand

Joined: Oct 29, 2003
Posts: 251
I am trying to layout an image with a Graphics2D object. How would I define a rectangle to add text to and have it center the text and break instead of going outside of the bounds of the rectangle?


http://www.goodercode.com
SCJP 1.4
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19216

Use FontMetrics to determine the width of your text:


SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
Kerry Wilson
Ranch Hand

Joined: Oct 29, 2003
Posts: 251
Thanks a lot, for some reason FontMetrics.getHeight() is returning 35 for my Font that is 30. However, the actual size of the font is more like 22. This is causing me problems with centering vertically. Also, what is the best way to do line wrapping?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19216

I think FontMetrics.getHeight takes into account some extra space so the letters on two lines won't touch each other. I can't think of any other reason.

Searching for spaces is usually the best way - search for the last space, get the substring until that space, until the width is just fine.
That leaves a cutting-off technique in case splitting at spaces (or whitespace in general) would still not solve the issue because some of the words are too long. You would need to broaden your splitting character set. -, / and \ are usually good candidates as well.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Center text on an image
 
Similar Threads
Image Merger
Scale the image
How to display text over an image in IE
help needed to reshape an image
image centering