如何在 Ruby 中计算字符串的宽度? [英] How do I calculate a String's width in Ruby?

查看:58
本文介绍了如何在 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

这篇关于如何在 Ruby 中计算字符串的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆