我试图在水平和垂直方向上准确地将文本放置在 Pane 的中心。使用 fontmetrics 和测试程序,我得到以下结果:
该测试提出以下问题:
最佳答案
这是 Frank 的 reportSize
的替代实现功能:
public void reportSize(String s, Font myFont) {
Text text = new Text(s);
text.setFont(myFont);
Bounds tb = text.getBoundsInLocal();
Rectangle stencil = new Rectangle(
tb.getMinX(), tb.getMinY(), tb.getWidth(), tb.getHeight()
);
Shape intersection = Shape.intersect(text, stencil);
Bounds ib = intersection.getBoundsInLocal();
System.out.println(
"Text size: " + ib.getWidth() + ", " + ib.getHeight()
);
}
此实现使用 shape intersection确定没有空格的渲染形状的边界框的大小。实现不依赖于
com.sun
Java 9+ 中的用户应用程序代码可能无法直接访问的包类。
关于fonts - JavaFX FontMetrics,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32237048/