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

前端 未结 5 1393
灰色年华
灰色年华 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(); 
    

提交回复
热议问题