Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prawn: anchor middle of the text to the given point

Prawn has height_of_formatted method to determine, well, height of formatted text, so its top left coordinate could be calculated when one needs to vertically align the middle of it to some anchor.

But there is no width_of_formatted method.

I'm drawing graph, and I need the text (dot label) to be centered right above some point (dot itself). So I know that middle of the text has x-coordinate of the dot.

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

like image 844
EugZol Avatar asked Oct 30 '22 21:10

EugZol


1 Answers

If you use bounding_box instead of draw_text you can specify the width of the bounding box for the text. Then if you centre-align the text you should be able to specify the exact x-coordinate of the middle. (it's the x-position of the box plus half the width)

Let's say you had a point at x-coordinate 72 and you want to put the label "hello world!" so the centre of the word is the same x-coordinate. You don't know how wide the word "hello" is but you're sure it'll fit inside a box of width 500.

72 - (500/2) = -178

bounding_box([-178, 100], :width => 500) do
  text "hello world!", align => :center
end
like image 104
Toby 1 Kenobi Avatar answered Nov 15 '22 07:11

Toby 1 Kenobi