开发者

Get the total width of a string rendered with an arbitrary .ttf font in Java Graphics 2

Currently we attempt to get the width of a string rendered with an arbitrary font.

BufferedImage img = new BufferedImage(10, 10, BufferedImage.TRANSLUCENT);
    img.createGraphics();
    Graphics2D g = (Graphics2D) img.getGraphics();
    g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);


    FontMetrics metrics = g.getFontMetrics(font);
    // get the height of a line of text in this font and render context
    int hgt = metrics.getHeight();
    // get the advance of my text in this font and render context
    int adv = met开发者_开发知识库rics.stringWidth(text);
    // calculate the size of a box to hold the text with some padding.
    //Dimension dim = new Dimension(adv + 2, hgt + 2);

The problem is with this line...

 int adv = metrics.stringWidth(text);

For most fonts this works but for some fancier script fonts it seems to break being less wide than we expected. As per the javadoc for FontMetrics.stringWidth you can even read...

Returns the total advance width for showing the specified String in this Font. The advance is the distance from the leftmost point to the rightmost point on the string's baseline. Note that the advance of a String is not necessarily the sum of the advances of its characters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜