目前我们尝试获取使用任意字体呈现的字符串的宽度。
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 = metrics.stringWidth(text);
// calculate the size of a box to hold the text with some padding.
//Dimension dim = new Dimension(adv + 2, hgt + 2);
问题出在这条线...
int adv = metrics.stringWidth(text);
对于大多数字体,这有效,但对于一些更高级的脚本字体,它似乎比我们预期的要宽。根据 FontMetrics.stringWidth 的 javadoc,您甚至可以阅读...
返回在此字体中显示指定字符串的总前进宽度。前进是字符串基线上从最左边点到最右边点的距离。请注意,字符串的前进不一定是其字符前进的总和。