Marcus Ataide
Marcus Ataide

Reputation: 7530

JavaFX font size from width

I want to calculate the Font Size due to a width value.

//Custom Font
Font.loadFont(Fonts.class.getResourceAsStream("/font/bignood/bignoodletoo.ttf"), 10)
String text = "Hello World";
Double width = 100;

Similiar SO Question to Java AWT

Similar SO Question to Java AWT 2


Edit: Use case

Think about a button that have a text "PLAY MONEY"¹. Now I will translate the text to PT_BR and it calls now "DINHEIRO FICTICIO"². As you can see, the word² is bigger than word¹, so if you set the same Font Size then you gonna see DINHEIRO FIC... inside the button.

So the mission here is get the width value of the Button, get the text and apply the Font Size to fit the full text inside the Button, whenever I change the text.

Upvotes: 4

Views: 1735

Answers (1)

Hugues M.
Hugues M.

Reputation: 20467

Below is a findFontSizeThatCanFit() method (and demo) that can be useful for this.

(See it in action online)

public class FxFontMetrics {
    public static void main(String[] args) {
        int maxWidth = 100;
        System.out.println("# Text -> Font size that can fit text under " + maxWidth + " pixels");
        Stream.of(
                "DINHEIRO FICTICIO",
                "Dinheiro ficticio",
                "PLAY MONEY",
                "Play money",
                "Devise factice qui compte pour du beurre")
                .forEach(text -> {
                    double size = findFontSizeThatCanFit(Font.font("dialog", 45), text, maxWidth);
                    System.out.println(text + " -> " + size);
                });
    }

    private static double findFontSizeThatCanFit(Font font, String s, int maxWidth) {
        double fontSize = font.getSize();
        double width = textWidth(font, s);
        if (width > maxWidth) {
            return fontSize * maxWidth / width;
        }
        return fontSize;
    }

    private static double textWidth(Font font, String s) {
        Text text = new Text(s);
        text.setFont(font);
        return text.getBoundsInLocal().getWidth();
    }
}

It prints:

# Text -> Font size that can fit text under 100 pixels
DINHEIRO FICTICIO -> 10.475703324808185
Dinheiro ficticio -> 12.757739986295396
PLAY MONEY -> 15.587183195068118
Play money -> 17.152428810720266
Devise factice qui compte pour du beurre -> 4.795354500327807

Upvotes: 6

Related Questions