如何在 JavaFX 中将文本居中放置在矩形中

How to center a text in a rectangle in JavaFX

我正在尝试使用 JavaFX GraphicsContext2D 在矩形的中心精确绘制一个字符串。 我不想使用 JavaFX 组件,所以请不要推荐它们。

例如,我描边一个矩形,其属性为:x = 10、y = 10、宽度 = 100、高度 = 100。现在我想描边文本的方式使其恰好位于中心(水平方向)和垂直)的矩形。我该怎么做?

作为@James_D , you can use the GraphicsContext methods setTextAlign() and setTextBaseline() to center the fillText() in an arbitrary Rectangle. Starting from this ,我在 tooltips 循环中添加了以下行以生成显示的图像:

gc.setTextAlign(TextAlignment.CENTER);
gc.setTextBaseline(VPos.CENTER);
gc.setFill(Color.BLACK);
gc.fillText(color.toString(),
    bounds.getX() + bounds.getWidth() / 2,
    bounds.getY() + bounds.getHeight() / 2);