views:

74

answers:

2

Im creating a servlet that renders a jpg/png with a given text. I want the text to be centered on the rendered image. I can get the width, but the height i'm getting seems to be wrong

Font myfont = new Font(Font.SANS_SERIF, Font.BOLD, 400);

BufferedImage image = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.setFont(myfont);
g.setColor(Color.BLACK);

FontMetrics fm = g.getFontMetrics();
Integer textwidth = fm.stringWidth(imagetext);
Integer textheight = fm.getHeight();

FontRenderContext fr = g.getFontRenderContext();
LineMetrics lm = myfont.getLineMetrics("5", fr );

float ascent = lm.getAscent();
float descent = lm.getDescent();
float height = lm.getHeight();

g.drawString("5", ((imagewidth - textwidth) / 2) , y?);
g.dispose();    

ImageIO.write(image, "png", outputstream);

These are the values I get: textwidth = 222 textheight = 504 ascent = 402 descent = 87 height = 503

Anyone know how to get the exact height om the "5" ? The estimated height should be around 250

+1  A: 

It's still a bit off, but much closer (288): ask the Glyph (the actual graphical representation)

GlyphVector gv = myfont.createGlyphVector(fr, "5");
Rectangle2D bounds = gv.getGlyphMetrics(0).getBounds2D();
float height = bounds.height();

Other Glyph methods (getGlyphVisualBounds, getGlyphPixelBounds, ...) return the same value. This is the region of the affected pixels when the glyph is drawn, so you won't get a better value IMO

king_nak
That solved it!
Tommy
A: 
FontRenderContext frc = gc.getFontRenderContext();
float textheight = (float) font.getStringBounds(comp.text, frc).getHeight();
Peter
this gives the same value (503) as the LineMetrics.getHeight()
Tommy