簡體   English   中英

確定JavaFX字體的寬度和高度

[英]Determining width and height of a JavaFX Font

我有一個Font對象,並且我需要字體的寬度和高度。 我知道getSize()返回字體的高度,因為字體的磅值通常是height ,但是在確定字體的寬度時我迷失了。

另外,能夠確定Font支持的每個特定字符的寬度也是一種可以接受的解決方案。

我的最佳猜測是使用loadFont方法時指定了寬度,但是文檔未指定size參數表示字體的寬度還是高度。

使用的所有字體都是等字體,例如DejaVu Sans MonoGNU FreeMonoLucida Sans Unicode

我遇到了同樣的問題,似乎沒有簡單的方法。 我的解決方案是使用正確的字體創建Text元素並檢查其大小:

double computeTextWidth(Font font, String text, double wrappingWidth) {
    Text helper = new Text();
    helper.setFont(font);
    helper.setText(text);
    // Note that the wrapping width needs to be set to zero before
    // getting the text's real preferred width.
    helper.setWrappingWidth(0);
    helper.setLineSpacing(0);
    double w = Math.min(helper.prefWidth(-1), wrappingWidth);
    helper.setWrappingWidth((int)Math.ceil(w));
    double textWidth = Math.ceil(helper.getLayoutBounds().getWidth());
    return textWidth;
}

如果我沒有記錯的話,這里的技巧是將prefWidth設置為-1。 參見JavaDoc

FontMetrics metrics = Toolkit.getToolkit().getFontLoader().getFontMetrics(font);
float charWidth = metrics.computeStringWidth("a");
float charHeight = metrics.getLineHeight();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM