2010-05-21 3 views
3

주어진 텍스트로 jpg/png를 렌더링하는 서블릿을 작성하고 있습니다. 텍스트를 렌더링 된 이미지의 가운데에 배치하고 싶습니다. 나는 폭을 얻을 수 있지만, 내가지고있어 높이가 잘못된 것 같다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); 

이 내가 얻는 값은 다음과 같습니다 textwidth = 222 되는 textHeight = 504 = 87 높이 상승 = 402 하강 = 503

"5"라는 정확한 높이를 얻는 방법을 아는 사람이 있습니까? 예상 높이 그것은 조금 여전히 꺼져

답변

3

250 주위해야하지만 훨씬 더 가까이 (288) 글리프 (실제 그래픽 표현)

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

다른 문양 방법 (getGlyphVisualBounds, getGlyphPixelBounds을 물어 .. .) 동일한 값을 반환합니다. 글리프를 그릴 때 영향을받는 픽셀의 영역이므로 더 좋은 값을 얻을 수 없습니다. IMO

+0

해결했습니다. – Tommy

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

이 값은 LineMetrics.getHeight()와 동일한 값 (503)을 제공합니다. – Tommy