How do you draw a string centered vertically in Java?

前端 未结 4 530
名媛妹妹
名媛妹妹 2020-12-24 03:00

I know it\'s a simple concept but I\'m struggling with the font metrics. Centering horizontally isn\'t too hard but vertically seems a bit difficult.

I\'ve tried usi

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-24 03:35

    Another option is the getBounds method from the TextLayout class.

    Font f;
    // code to create f
    String TITLE = "Text to center in a panel.";
    FontRenderContext context = g2.getFontRenderContext();
    
    TextLayout txt = new TextLayout(TITLE, f, context);
    Rectangle2D bounds = txt.getBounds();
    int xString = (int) ((getWidth() - bounds.getWidth()) / 2.0 );
    int yString = (int) ((getHeight() + bounds.getHeight()) / 2.0);
    // g2 is the graphics object 
    g2.setFont(f);
    g2.drawString(TITLE, xString, yString);
    

提交回复
热议问题