【问题标题】:Cannot get right height of text in java.awt.BufferdImage/Graphics2D无法在 java.awt.BufferdImage/Graphics2D 中获得正确的文本高度
【发布时间】:2011-02-22 07:27:20
【问题描述】:

我正在创建一个 servlet,它使用给定的文本呈现 jpg/png。我希望文本以渲染图像为中心。我可以得到宽度,但我得到的高度似乎是错误的

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 文本高度 = 504 上升 = 402 下降 = 87 高度 = 503

有人知道如何得到“5”的准确高度吗?估计高度应该在 250 左右

【问题讨论】:

    标签: java awt graphics2d


    【解决方案1】:

    它仍然有点偏离,但更接近 (288):问 Glyph(实际的图形表示)

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

    其他 Glyph 方法(getGlyphVisualBounds、getGlyphPixelBounds、...)返回相同的值。这是绘制字形时受影响像素的区域,因此您不会得到更好的值 IMO

    【讨论】:

      【解决方案2】:
      FontRenderContext frc = gc.getFontRenderContext();
      float textheight = (float) font.getStringBounds(comp.text, frc).getHeight();
      

      【讨论】:

      • 这给出了与 LineMetrics.getHeight() 相同的值 (503)
      猜你喜欢
      • 1970-01-01
      • 2017-04-11
      • 2015-10-04
      • 1970-01-01
      • 2014-11-10
      • 2011-05-20
      • 2018-12-03
      • 2018-10-09
      • 1970-01-01
      相关资源
      最近更新 更多