我創建了一個呈現給定文本的jpg/png的servlet。我希望文字以渲染圖像爲中心。我能得到的寬度,但我得到的高度似乎是錯誤的無法在java.awt.BufferdImage/Graphics2D中獲取文本的正確高度
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);
這是我得到的值: 文本寬度= 222 textHeight不同= 504 上升= 402 血統= 87 高度= 503
任何人都知道如何獲得「5」的確切身高?估計身高應該在250
解決了它! – Tommy 2010-05-21 14:09:58