How to calculate the font's width?

后端 未结 6 1529
眼角桃花
眼角桃花 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条回答
  •  -上瘾入骨i
    2020-12-15 10:33

    For a single string, you can obtain the metrics for the given drawing font, and use that to calculate the string size. For example:

    String      message = new String("Hello, StackOverflow!");
    Font        defaultFont = new Font("Helvetica", Font.PLAIN, 12);
    FontMetrics fontMetrics = new FontMetrics(defaultFont);
    //...
    int width = fontMetrics.stringWidth(message);
    

    If you have more complex text layout requirements, such as flowing a paragraph of text within a given width, you can create a java.awt.font.TextLayout object, such as this example (from the docs):

    Graphics2D g = ...;
    Point2D loc = ...;
    Font font = Font.getFont("Helvetica-bold-italic");
    FontRenderContext frc = g.getFontRenderContext();
    TextLayout layout = new TextLayout("This is a string", font, frc);
    layout.draw(g, (float)loc.getX(), (float)loc.getY());
    
    Rectangle2D bounds = layout.getBounds();
    bounds.setRect(bounds.getX()+loc.getX(),
                  bounds.getY()+loc.getY(),
                  bounds.getWidth(),
                  bounds.getHeight());
    g.draw(bounds);
    

提交回复
热议问题