2013-04-04 29 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