String length in pixels in Java

后端 未结 3 1237
抹茶落季
抹茶落季 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 11:02

    This gives the output of (137.0, 15.09375) for me. I have no idea what the units are, but it certainly looks proportionally correct and doesn't use Graphics2D directly.

        Font f = new Font("Ariel", Font.PLAIN, 12);
        Rectangle2D r = f.getStringBounds("Hello World! Hello World!", new FontRenderContext(null, RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT, RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT));
        System.out.println("(" + r.getWidth() + ", " + r.getHeight() + ")"); 
    

提交回复
热议问题