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

前端 未结 5 1404
灰色年华
灰色年华 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: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.

提交回复
热议问题