How to calculate the font's width?

后端 未结 6 1534
眼角桃花
眼角桃花 2020-12-15 09:52

I am using java to draw some text, but it is hard for me to calculate the string\'s width. for example: zheng中国... How long will this string occupy?

6条回答
  •  隐瞒了意图╮
    2020-12-15 10:26

    You can find it from Font.getStringBounds():

    String string = "Hello World";
    // Passing or initializing an instance of Font.
    Font font = ...;
    int width = (int) font.getStringBounds(string, new FontRenderContext(font.getTransform(), false, false)).getBounds().getWidth();
    

提交回复
热议问题