以下是可用於此的findFontSizeThatCanFit()
方法(和演示)。
(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();
}
}
它打印:
# 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
你能想得到的寬度(就像一個場景或某事),你可以在一個更具體一點,怎麼大你想要將字體與它進行比較? – Austin
@奧斯汀,我將從按鈕,標籤e等得到的寬度。任何具有文本的對象。帶有自定義字體的文本需要符合正確的寬度值。 – Marckaraujo
該文本需要適合還是'Button' /'Label'?後者2包括文本的邊距... – fabian