[英]Getting text bounds within JavaFX
我正在使用JavaFX生成音樂文檔的位圖預覽。
在繪制過程中的某些時候,我需要知道給定弦的尺寸。
到目前為止,我已經使用了以下內容:
bounds = TextBuilder.create().text(string).font(m_Font).build().getLayoutBounds();
但是,日食告訴我這已經貶值了。 它是如此貶值,以至於bounds對象為空(全部設置為零)。
我現在該如何獲取單個線串的邊界(寬度和高度)?
請注意, 沒有任何屏幕上的控件用於顯示這些內容。 一切都在內存中生成,然后“轉儲”到png位圖。
我已經在網上掃盪了,卻找不到答案( 或者我完全錯過了答案)。
有專家幫助嗎?
正如我在評論中提到的那樣,不建議棄用getLayoutBounds()
,並且完全可以使用。 只是過時的構建器。
就是說,我創建了以下測試應用程序,使用構建器並直接創建對象,該應用程序產生了看似正確的輸出:
import javafx.geometry.Bounds;
import javafx.scene.text.Text;
import javafx.scene.text.TextBuilder;
import javafx.stage.Stage;
import javafx.scene.text.Font;
public class stack extends javafx.application.Application {
public static void main(String[] args)
{
// Builder
Bounds b = TextBuilder.create().text("hello").build().getLayoutBounds();
System.out.println(b.getHeight() + ", " + b.getWidth());
b = TextBuilder.create().text("heeeeello").build().getLayoutBounds();
System.out.println(b.getHeight() + ", " + b.getWidth());
// No builder
b = new Text("hello").getLayoutBounds();
System.out.println(b.getHeight() + ", " + b.getWidth());
b = new Text("heeeeello").getLayoutBounds();
System.out.println(b.getHeight() + ", " + b.getWidth());
// With bad font, zero sized
Font my_font = new Font("i am not a font", 0);
Text text = new Text("heeeeello");
text.setFont(my_font);
b = text.getLayoutBounds();
System.out.println(b.getHeight() + ", " + b.getWidth());
// With bad font, arbitrary size
my_font = new Font("i am not a font", 20);
text = new Text("heeeeello");
text.setFont(my_font);
b = text.getLayoutBounds();
System.out.println(b.getHeight() + ", " + b.getWidth());
}
@Override
public void start(Stage primaryStage) throws Exception { }
}
輸出:
15.9609375, 25.91015625
15.9609375, 51.01171875
15.9609375, 25.91015625
15.9609375, 51.01171875
0.0, 0.0
26.6015625, 85.01953125
我假設您的字體搞砸了 ,可能大小設置為零或其他錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.