String length in pixels in Java

后端 未结 3 1245
抹茶落季
抹茶落季 2021-01-11 10:32

Is there a way to calculate the length of a string in pixels, given a certain java.awt.Font object, that does not use any GUI components?

3条回答
  •  长情又很酷
    2021-01-11 10:58

    You can use the Graphics2D object to get the font bounds (including the width):

    Graphics2D g2d = ...
    Font font = ...
    Rectangle2D f = font.getStringBounds("hello world!", g2d.getFontRenderContext());
    

    But that depends on how you will get the Graphics2D object (for example from an Image).

提交回复
热议问题