获取 Java Graphics 2 中使用任意 .ttf 字体呈现的字符串的总宽度
目前我们尝试获取使用任意字体呈现的字符串的宽度。
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,您甚至可以阅读...
返回显示指定字符串的总提前宽度 这个字体。前进是从最左边的点到 字符串基线上的最右边的点。 请注意,a的推进 字符串不一定是其字符的进步之和。
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 = metrics.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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论