如何在 Ruby 中计算字符串的宽度?

问题描述:

String.length 只会告诉我字符串中有多少个字符.(其实在 Ruby 1.9 之前,它只会告诉我有多少字节,更没用.)

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

我真的很想知道一个字符串有多少个en"宽.例如:

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

如果我能得到字符串的第一个 n 就更好了:

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"

如果我可以为整个事情制定策略,那就更好了.有些人认为一个空格应该是 0.25en,有些人认为应该是 0.33,等等.

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.

您应该使用 RMagick gem 使用您想要的字体渲染Draw"对象(您可以加载 .ttf 文件等)

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

代码看起来像这样:

   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

您可以在我的按钮制作工具中看到它的效果:http://risingcode.com/button/everybodywangchungtonite

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