• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Center text on an image

 
Kerry Wilson
Ranch Hand
Posts: 254
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Rob Spoor
Sheriff
Pie
Posts: 20514
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use FontMetrics to determine the width of your text:
 
Kerry Wilson
Ranch Hand
Posts: 254
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20514
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic