【问题标题】:How do I calculate the width of a string in pixels?如何计算字符串的宽度(以像素为单位)?
【发布时间】:2013-08-22 01:51:55
【问题描述】:

如何在 Java 中以像素为单位计算 String 的宽度? 例如,我有一个字符串说“Hello World!”。它的像素长度是多少,还要考虑它的字体系列和大小?

【问题讨论】:

标签: java string fonts width


【解决方案1】:

简而言之:问题取决于您使用的框架。例如,如果您使用 AWT,并且有一个 Graphics 对象 graphics 和一个 Font 对象 font,您可以执行以下操作:

FontMetrics metrics = graphics.getFontMetrics(font);
int width = metrics.stringWidth("Hello world!");

查看this了解更多信息。

【讨论】:

    【解决方案2】:

    你可以试试这样的

    Graphics2D g2d = ...
    Font font = ...
    Rectangle2D r = font.getStringBounds("hello world!", g2d.getFontRenderContext());
    System.out.println("(" + r.getWidth() + ", " + r.getHeight() + ")");
    

    参考这个doc,可能对你有帮助。

    【讨论】:

    • 考虑到您可以使用Graphics#getFontMetrics,这似乎有点值得考虑,但我会为您的与众不同投赞成票;)
    【解决方案3】:

    根据您想要实现的目标,有多种方法可以实现您想要的目标,例如...

    BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = img.createGraphics();
    FontMetrics fm = g2d.getFontMetrics();
    System.out.println(fm.stringWidth("This is a simple test"));
    g2d.dispose();
    

    但这仅与 BufferedImageGraphics 上下文相关,它不会转译为屏幕或打印机之类的东西。

    但是,只要你有一个Graphics 上下文,你就可以获得相同的结果。

    显然,此示例使用为 Graphics 上下文安装的默认字体,如果需要,您可以更改...

    【讨论】:

    • 我只有一个String。我知道它的长度、字体系列、字体大小。我想以像素为单位计算它的大小。
    • 很好,那么你可以使用类似上面的东西。宽度和高度取决于您要渲染到的 Graphics 上下文。虽然您拥有字体系列、字体大小和文本,但您缺少关键元素
    【解决方案4】:

    有几种方法可以做到这一点,如果文本在标签中,您可以尝试 label.getElement().getClientWidth();,如果您使用 AWT,则可以使用 Graphics.getFontMetrics 然后 FontMetrics.stringWidth

    【讨论】:

      【解决方案5】:

      您可以使用FontMetrics。 FontMetrics 类定义了一个字体度量对象,它封装了有关在特定屏幕上呈现特定字体的信息。

      您可以执行以下操作

          Font font = new Font("Verdana", Font.PLAIN, 10);  
          FontMetrics metrics = new FontMetrics(font) {  
          };  
          Rectangle2D bounds = metrics.getStringBounds("Hello World!", null);  
          int widthInPixels = (int) bounds.getWidth(); 
      

      【讨论】:

      • 我感觉这行不通。像素大小将取决于 Graphics 上下文,您将其传递给 null for...
      • 不确定如何交叉验证结果,但是当我运行它时,我得到 67 作为字符串 Hello World! 的输出。
      猜你喜欢
      • 2011-09-15
      • 2014-07-16
      • 1970-01-01
      • 1970-01-01
      • 2011-06-28
      • 1970-01-01
      • 2016-12-11
      • 2013-06-17
      • 1970-01-01
      相关资源
      最近更新 更多