Getting string size in java (without having a Graphics object available)

前端 未结 6 609
南方客
南方客 2021-01-11 12:37

I\'m trying to write application which need to draw many strings using Graphics2D class in Java. I need to get sizes of each String object (to calculate exact p

6条回答
  •  独厮守ぢ
    2021-01-11 13:26

    Here is a snippet of code that does something similar -- wrote it for abbreviating the string to a given number of pixels.

    public static String abbreviate(final Graphics2D g2, final String text, final int fitToWidth) {
         // define how many characters in the caption can be drawn
         final FontMetrics fm = g2.getFontMetrics();
         Rectangle2D textBounds = fm.getStringBounds(text, g2);
         int count = text.length();
         while ((textBounds.getWidth() > fitToWidth) && (count > 4)) {
             textBounds = fm.getStringBounds(text.substring(0, count--), g2);
         }
         return count == text.length() ? text : StringUtils.abbreviate(text, count);
    }
    

提交回复
热议问题