Unable to get the correct text height in java.awt.BufferdImage / Graphics2D

Im creating a servlet that displays jpg / png with the given text. I want the text to be centered on the displayed image. I can get the width, but the height I get seems 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 ascent = 87 height = 503

Does anyone know how to get the exact height from "5"? Estimated height should be around 250

+3
source share
2 answers

This is still a bit, but much closer (288): ask the Symbol (actual graphic representation)

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

Glyph (getGlyphVisualBounds, getGlyphPixelBounds,...) . , , IMO

+3
FontRenderContext frc = gc.getFontRenderContext();
float textheight = (float) font.getStringBounds(comp.text, frc).getHeight();
0

Source: https://habr.com/ru/post/1746546/


All Articles