1. I accept that I am under the control of a higher power (Muppet).

wtf?  how do you get a TextLayout thingie in java to tell you...

...how wide and high the text is before you create the image into which it is to be drawn?

AFAICT you need to create the image before you create the text layout thingie, and the image needs to be big enough and so on?


clearly Im overlooking something stupid here.
Permalink Send private email zestyZucchini 
March 10th, 2007 8:36pm
I've solved this problem before, but the code is on my work computer. I'll let you know next time I switch it on if nobody has given you the answer before then.
Permalink Send private email bon vivant 
March 10th, 2007 9:05pm
thanks.  Im hacking together a rather messy solution that will/should work, but I would dearly love to swap it out for something decent.
Permalink Send private email zestyZucchini 
March 10th, 2007 9:13pm
Here's a template for figuring out the width and height of some text given the font that it's to be drawn in:

  // get hold of a Graphics2D reference from somewhere
  // "thing" and "getThingy()" depend on your context
  Graphics2D g2 = (Graphics2D) thing.getThingy().getGraphics();
  // get a font rendering context
  FontRenderContext frc = g2.getFontRenderContext();
  // identify the font the string is to be drawn in
  Font myFont = new Font(fontName, fontType, fontSize);
  // get the width of myString in pixels when rendered in the specified font
  int width = (int) myFont.getStringBounds(myString, frc).getWidth();
  // height similarly

Note that g2 could possibly get returned as null and it would be as well to put in an error check for that.
Permalink Send private email bon vivant 
March 11th, 2007 12:59am
bah.  why is everything in programming both easy and embarrassingly obvious once you know how?

thanks again bon vivant, thats somewhat shorter and _way_ more pleasant on the eyes than my version.
Permalink Send private email zestyZucchini 
March 11th, 2007 3:36am

This topic is archived. No further replies will be accepted.

Other topics: March, 2007 Other topics: March, 2007 Recent topics Recent topics