Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the font's width?

Tags:

java

string

width

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?

like image 312
MemoryLeak Avatar asked Oct 06 '09 10:10

MemoryLeak


People also ask

How do I determine the width of a font?

Right click on the page you like the look of and select Inspect Element (Firefox), Inspect (Chrome), or F12 Developer Tools (Edge). Select Inspector (Firefox) or Computed (Chrome) in the new bottom windows and scroll down on the right until you reach Font or font-size.

How do you find the width of a DOM element?

Use offsetWidth & offsetHeight properties of the DOM element to get its the width and height.

What width is font-size?

Typographers measure the cap height of a font in units called points. A point is 1/72nd of an inch. There are twelve points in a pica, and six picas equal one inch. The width of each character is called the set width.

Does font-size refer to height or width?

The font-size property specifies the size of the font, no matter what unit is used. The size of a font can be characterized as the height of the font, but even this is just a loose and pragmatic description; characters may extend above and below the levels defined by the size of the font.


4 Answers

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);
like image 113
gavinb Avatar answered Nov 04 '22 17:11

gavinb


See Graphics.getFontMetrics() and FontMetrics.stringWidth().

like image 42
Bombe Avatar answered Nov 04 '22 16:11

Bombe


here is a simple app that can show you how to use FontMetrics when testing the width of a String:

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class GUITest {
    JFrame frame;
    public static void main(String[] args){
        new GUITest();
    }
    public GUITest() {
        frame = new JFrame("test");
        frame.setSize(300,300);
        addStuffToFrame();
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                frame.setVisible(true);
            }
        });
    }           

    private void addStuffToFrame() {    
        JPanel panel = new JPanel(new GridLayout(3,1));
        final JLabel label = new JLabel();
        final JTextField tf = new JTextField(); 
        JButton b = new JButton("calc sting width");
        b.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                FontMetrics fm = label.getFontMetrics(label.getFont());
                String text = tf.getText();
                int textWidth = fm.stringWidth(text);
                label.setText("text width for \""+text+"\": " +textWidth);
            }
        });
        panel.add(label);
        panel.add(tf);
        panel.add(b);
        frame.setContentPane(panel);
    }


}
like image 44
akf Avatar answered Nov 04 '22 15:11

akf


Take a look at this great presentation, especially "Text Measurement" part. It explains available sizes and their uses: Advanced Java 2D™ topics for Desktop Applications.

Some more information in Java2D FAQ: What is the difference between logical, visual and pixel bounds?

like image 23
Peter Štibraný Avatar answered Nov 04 '22 17:11

Peter Štibraný