Cannot get right height of text in java.awt.BufferdImage/Graphics2D

Posted by Tommy on Stack Overflow See other posts from Stack Overflow or by Tommy
Published on 2010-05-21T10:57:08Z Indexed on 2010/05/21 11:20 UTC
Read the original article Hit count: 403

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about java

Related posts about awt