开发者

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

开发者 https://www.devze.com 2022-12-30 22:34 出处:网络
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

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.disp开发者_如何学运维ose();    

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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消