How do I calculate the width of a string in pixels?

前端 未结 5 1378
灰色年华
灰色年华 2020-12-18 07:11

How to calculate width of a String in pixels in Java? For e.g., I have a string say \"Hello World!\". What is its length in pixels, also considering its fon

相关标签:
5条回答
  • 2020-12-18 07:33

    You can use FontMetrics. The FontMetrics class defines a font metrics object, which encapsulates information about the rendering of a particular font on a particular screen.

    You can do something like below

        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(); 
    
    0 讨论(0)
  • 2020-12-18 07:42

    You can try something like this

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

    Refer this doc, may help you.

    0 讨论(0)
  • 2020-12-18 07:48

    In short: the question depends on the framework you are using. For example, if you are using AWT, and have a Graphics object graphics, and a Font object font you can do the following:

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

    Check out this for more information.

    0 讨论(0)
  • 2020-12-18 07:50

    There are a number of ways to achieve what you want, based on what it is you want to achieve, for example...

    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();
    

    But this only has relevence for the BufferedImage and it's Graphics context, it will not translate back to say, something like a screen or printer.

    However, so long as you have a Graphics context, you can achieve the same result.

    This example, obviously, uses the default font installed for the Graphics context, which you can change if you need to...

    0 讨论(0)
  • 2020-12-18 07:52

    there are couple of ways to do it, you can try label.getElement().getClientWidth(); if the text is in a lable, if you're using AWT you can use Graphics.getFontMetrics then FontMetrics.stringWidth

    0 讨论(0)
提交回复
热议问题