Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - FontMetrics without Graphics

How to get FontMetrics without use Graphics ? I want to get FontMetrics in constructor, now I do this way:

BufferedImage bi = new BufferedImage(5, 5, BufferedImage.TYPE_INT_RGB); FontMetrics fm = bi.getGraphics().getFontMetrics(font); int width = fm.stringWidth(pattern); int height = fm.getHeight(); 
like image 395
piotrek Avatar asked May 16 '10 11:05

piotrek


People also ask

What is FontMetrics in Java?

The FontMetrics class defines a font metrics object, which encapsulates information about the rendering of a particular font on a particular screen.

What is setFont in Java?

setFont(Font f) Set the Font of this object. Constructors in java.awt with parameters of type Font. Constructor and Description.

What are font metrics?

Font metrics are measurements of text rendered by a Font object such as the height of a line of text in the font. The most common way to measure text is to use a FontMetrics instance which encapsulates this metrics information.

What do you understand by Font Matrix?

April 2017) (Learn how and when to remove this template message) Fontmatrix is a font manager for Linux desktop environments. It can manage fonts installed system-wide or for individual user accounts. It relies on FreeType to render font samples, and on Qt for its user interface.


2 Answers

No you do not necessarily need to get/use the graphics object:

Font font = new Font("Helvetica",Font.PLAIN,12); Canvas c = new Canvas(); FontMetrics fm = c.getFontMetrics(font); 

If you would now call c.getGraphics() it would return null. The canvas solution on the other hand will also work in headless mode.

like image 83
Lonzak Avatar answered Sep 28 '22 15:09

Lonzak


Hmm... It is quite logical that you need graphics to get FontMetrics. Font height, width etc. can differ on various displays.

If you have some Component, you can use it for getting FontMetrics:

component.getFontMetrics(font); 
like image 36
amorfis Avatar answered Sep 28 '22 14:09

amorfis