01 October 2010

Measure the width and height, in pixels, of a piece of text in a String, for a specific Font

static public Dimension getTextDimensions(String text, Component component, Font font) {
       FontMetrics fm = component.getFontMetrics(font);
       int[] ws = fm.getWidths(); // for the first 256 characters
       int height = fm.getHeight();
       int width = 0;
       for (int i=text.length() -1; i>-1; i--) {
              int c = (int)text.chatAt(i);
              if (c < 256) {
              width += ws[c];
       } // else ignore character
       return new Dimension(width, height);
}


String text = "some text";
Font font = new Font("SansSerif", Font.PLAIN, 12);
Component c = ...; // your window frame, for example, or a JLabel, etc.

Dimension dim = getTextDimensions(text, c, font);

No comments:

Post a Comment