获取 Java Graphics 2 中使用任意 .ttf 字体呈现的字符串的总宽度

发布于 2024-12-07 04:48:30 字数 1112 浏览 0 评论 0原文

目前我们尝试获取使用任意字体呈现的字符串的宽度。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文