Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I calculate a String's width in Ruby?

String.length will only tell me how many characters are in the String. (In fact, before Ruby 1.9, it will only tell me how many bytes, which is even less useful.)

I'd really like to be able to find out how many 'en' wide a String is. For example:

'foo'.width
# => 3

'moo'.width
# => 3.5          # m's, w's, etc. are wide

'foi'.width
# => 2.5          # i's, j's, etc. are narrow

'foo bar'.width
# => 6.25         # spaces are very narrow

Even better would be if I could get the first n en of a String:

'foo'[0, 2.en]
# => "fo"

'filial'[0, 3.en]
# => "fili"

'foo bar baz'[0, 4.5en]
# => "foo b"

And better still would be if I could strategize the whole thing. Some people think a space should be 0.25en, some think it should be 0.33, etc.

like image 376
James A. Rosen Avatar asked Dec 18 '08 19:12

James A. Rosen


1 Answers

You should use the RMagick gem to render a "Draw" object using the font you want (you can load .ttf files and such)

The code would look something like this:

   the_text = "TheTextYouWantTheWidthOf"
   label = Draw.new
   label.font = "Vera" #you can also specify a file name... check the rmagick docs to be sure
   label.text_antialias(true)
   label.font_style=Magick::NormalStyle
   label.font_weight=Magick::BoldWeight
   label.gravity=Magick::CenterGravity
   label.text(0,0,the_text)
   metrics = label.get_type_metrics(the_text)
   width = metrics.width
   height = metrics.height

You can see it in action in my button maker here: http://risingcode.com/button/everybodywangchungtonite

like image 183
diclophis Avatar answered Oct 20 '22 11:10

diclophis