Shrimp: snap the middle of the text to a given point

Prawn has a height_of_formatted method to determine the height of the formatted text, so its upper left coordinate could be calculated when you need to vertically align the middle of it to some anchor.

But there is no width_of_formatted method.

I draw a graph, and I need the text (point label) to be centered right above some point (the point itself). Therefore, I know that in the middle of the text there is the x-coordinate of the point.

How to get the x-coordinate of the beginning of the text (so that I can provide it to draw_text and other rendering methods)?

+5
source share
1 answer

If you use bounding_box instead of draw_text , you can specify the width of the bounding box for the text. Then, if you center the text, you must specify the exact x coordinate for the middle. (this is the x-position of the window plus half the width)

Say you have a dot at the x-coordinate of 72, and you want to label "hello world!". therefore, the center of the word is the same x-coordinate. You do not know how widespread the word "hello" is, but you are sure that it will be placed in a box with a width of 500.

72 - (500/2) = -178

 bounding_box([-178, 100], :width => 500) do text "hello world!", align => :center end 
+2
source

All Articles