How to Change Font Size in drawString Java

前端 未结 6 1684
清歌不尽
清歌不尽 2021-02-02 07:33

How to make the font size bigger in g.drawString(\"Hello World\",10,10); ?

6条回答
  •  野的像风
    2021-02-02 07:54

    Because you can't count on a particular font being available, a good approach is to derive a new font from the current font. This gives you the same family, weight, etc. just larger...

    Font currentFont = g.getFont();
    Font newFont = currentFont.deriveFont(currentFont.getSize() * 1.4F);
    g.setFont(newFont);
    

    You can also use TextAttribute.

    Map attributes = new HashMap<>();
    
    attributes.put(TextAttribute.FAMILY, currentFont.getFamily());
    attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD);
    attributes.put(TextAttribute.SIZE, (int) (currentFont.getSize() * 1.4));
    myFont = Font.getFont(attributes);
    
    g.setFont(myFont);
    

    The TextAttribute method often gives one even greater flexibility. For example, you can set the weight to semi-bold, as in the example above.

    One last suggestion... Because the resolution of monitors can be different and continues to increase with technology, avoid adding a specific amount (such as getSize()+2 or getSize()+4) and consider multiplying instead. This way, your new font is consistently proportional to the "current" font (getSize() * 1.4), and you won't be editing your code when you get one of those nice 4K monitors.

提交回复
热议问题