Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX FontMetrics

Tags:

fonts

javafx

I'm trying to place text accurately in the centre of a pane both horizontally and vertically. Using fontmetrics and a test program I get the following results:

enter image description here

This test raises the following questions:

  1. Why is the ascent value (top black line) so high? I expected it to go across the top of the 'T'. The magenta line is the 'lineheight' value, so I assume that's the baseline for any text above it.
  2. If the black line includes line spacing, why is there no measurement for the top of the 'T'?
  3. Is there a way to get an accurate bounding box or do I have to graphically linescan a text image to find the boundaries? Obviously the left and right values also include some sort of spacing, so a scan would seem to be the only solution.
like image 668
Frank Avatar asked Aug 26 '15 21:08

Frank


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 ascent and descent in font?

Ascent - The recommended distance above the baseline for singled spaced text. Descent - The recommended distance below the baseline for singled spaced text. Bottom - The maximum distance below the baseline for the lowest glyph in the font at a given text size.

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.


1 Answers

Here is an alternate implementation of Frank's reportSize function:

public void reportSize(String s, Font myFont) {
    Text text = new Text(s);
    text.setFont(myFont);
    Bounds tb = text.getBoundsInLocal();
    Rectangle stencil = new Rectangle(
            tb.getMinX(), tb.getMinY(), tb.getWidth(), tb.getHeight()
    );

    Shape intersection = Shape.intersect(text, stencil);

    Bounds ib = intersection.getBoundsInLocal();
    System.out.println(
            "Text size: " + ib.getWidth() + ", " + ib.getHeight()
    );
}

This implementation uses shape intersection to determine the size of the bounding box of the rendered shape with no whitespace. The implementation does not rely on com.sun package classes which may not be directly accessible to user application code in Java 9+.

like image 169
jewelsea Avatar answered Oct 24 '22 17:10

jewelsea