以下は、これに役立つ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
@Austin、ボタンからの幅、ラベルeなど。テキストを持つオブジェクト。カスタムフォントのテキストは、正確に幅の値に収まる必要があります。 – Marckaraujo
テキストは 'Button' /' Label'に収まる必要がありますか?後者2にはテキストの余白が含まれています。 – fabian