2013-04-04 21 views
1

这是返回AWT的字体字符为BufferedImage的方法:不能得到正确的宽度字体烧焦

private BufferedImage getCharImage(char ch) { 
    BufferedImage sizeImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); 
    Graphics2D sizeGraphics = (Graphics2D) sizeImage.getGraphics(); 
    if (antiAlias) { 
     sizeGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
    } 

    FontMetrics fontMetrics = sizeGraphics.getFontMetrics(font); 
    int charwidth = fontMetrics.charWidth(ch); 
    if (charwidth <= 0) { 
     charwidth = 1; 
    } 

    int charheight = fontMetrics.getHeight(); 
    if (charheight <= 0) { 
     charheight = fontSize; 
    } 

    BufferedImage charImage = new BufferedImage(charwidth, charheight, BufferedImage.TYPE_INT_ARGB); 
    Graphics2D charGraphics = (Graphics2D) charImage.getGraphics(); 

    if (antiAlias) { 
     charGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
    } 

    charGraphics.setFont(font); 
    charGraphics.setColor(Color.WHITE); 
    charGraphics.drawString(String.valueOf(ch), 0, fontMetrics.getAscent()); 

    return charImage; 
} 

的问题是,我得到不正确的宽度,和人物不适合装箱缓冲图像。如果我要创建像这样的缓存图像new BufferedImage(charwidth + 10, charheight, BufferedImage.TYPE_INT_ARGB);这些字符将适合图像(这意味着我得到错误的字体宽度)。 为什么我面对这个问题,我该如何修复它?我使用arialbi.ttf(粗体,斜体)。

这是字体的渲染 enter image description here

编辑:

我这是怎么定义字体变量:

font = Font.createFont(Font.TRUETYPE_FONT, inputStream); 
    font = font.deriveFont(fontSize); 
+0

请让我知道如果你要我澄清一些东西。 – Qualphey 2013-04-04 16:15:38

+0

显示你如何定义你的'font'变量。 – whiskeyspider 2013-04-04 17:21:43

+0

字体大小为124 – Qualphey 2013-04-04 18:34:23

回答

2

我想这是因为提前,或charWidth()与由字体定义的字符的实际宽度没有太大关系。

JavadocFontMetrics.charWidth(char ch)

advance是从最左边的点到最右边的 点上的字符的基线

像赞善斜体“G”,下面的一个字符的距离基线,延伸到最小x的左侧。或同一字体中的“s”延伸到基线以上的最大x的右侧。在较直的字体中,如Arial Regular,advance(基线宽度)恰好与字符的实际宽度非常接近。

我不确定除了添加任意填充之外还有一个很好的解决方案。

参见:http://docs.oracle.com/javase/tutorial/2d/text/measuringtext.html

+0

对于任何感兴趣的人来说,角色两侧的垫子都称为左侧轴承和右侧轴承,并且相对于前进宽度可以是正值或负值。微软有一个很好的例子[这里](https://msdn.microsoft.com/en-us/library/system.windows.media.glyphtypeface(v = vs.110).aspx)。 – user1620220 2016-12-27 15:42:30