0

I am trying to draw a string exactly in the center of a rectangle using JavaFX GraphicsContext2D. I don't want to use JavaFX components so please do not recommend them.

For example, I stroke a rectangle with attributes: x = 10, y = 10, width = 100, height = 100. Now I want to stroke a text in a way that it comes exactly in the center(horizontally and vertically) of the rectangle. How can I do it?

Navid Naseri
  • 123
  • 7
  • 3
    Does calling `setTextAlign(TextAlignment.CENTER);` and `setTextBaseline(VPos.CENTER)`, and then positioning the text at the Center of the rectangle (55,55) not work? – James_D Jul 16 '21 at 22:08
  • 1
    For context, also see the related question: [how to put a text into a circle object to display it from circle's center?](https://stackoverflow.com/questions/17437411/how-to-put-a-text-into-a-circle-object-to-display-it-from-circles-center), which discusses the [text bounds type](https://openjfx.io/javadoc/16/javafx.graphics/javafx/scene/text/Text.html#boundsTypeProperty). Note that text bounds type can't be set for canvas as far as I can tell and is more applicable when using layout managers in the scene graph, so this answer is probably not directly applicable to your situation. – jewelsea Jul 19 '21 at 18:11
  • 1
    A related example is examined [here](https://stackoverflow.com/a/46998782/230513). You may have a good reasons to confine rendering to a single `Node` of type `Canvas`; it's as close to the host platform's rendering pipeline as your likely to get, but you have to manage all the geometry yourself. Don't hesitate to re-examine the decision as your understanding evolves. – trashgod Jul 19 '21 at 22:14

1 Answers1

4

As @James_D comments, you can use the GraphicsContext methods setTextAlign() and setTextBaseline() to center the fillText() in an arbitrary Rectangle. Starting from this example, I added the following lines in the tooltips loop in order to produce the image shown:

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);

image

trashgod
  • 203,806
  • 29
  • 246
  • 1,045