How to calculate width of a String
in pixels in Java? For e.g., I have a string say \"Hello World!\". What is its length in pixels, also considering its fon
You can use FontMetrics. The FontMetrics class defines a font metrics object, which encapsulates information about the rendering of a particular font on a particular screen.
You can do something like below
Font font = new Font("Verdana", Font.PLAIN, 10);
FontMetrics metrics = new FontMetrics(font) {
};
Rectangle2D bounds = metrics.getStringBounds("Hello World!", null);
int widthInPixels = (int) bounds.getWidth();