我想根据宽度值计算字体大小.
//Custom Font
Font.loadFont(Fonts.class.getResourceAsStream("/font/bignood/bignoodletoo.ttf"), 10)
String text = "Hello World";
Double width = 100;
Run Code Online (Sandbox Code Playgroud)
编辑:用例
想想一个有文字的按钮"PLAY MONEY"¹.现在我将文本翻译为PT_BR并立即调用"DINHEIRO FICTICIO"².如你所见,单词²大于单词¹,所以如果你设置相同,Font Size那么你会看到DINHEIRO FIC...按钮内部.
因此,每当我改变时,这里的任务就是得到它的width值Button,得到text并应用Font Size以适应全文.Buttontext
下面是一个findFontSizeThatCanFit()可用于此的方法(和演示).
(在线观看)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
它打印:
# 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
Run Code Online (Sandbox Code Playgroud)