7

String.length文字列に含まれる文字数のみを教えてくれます。(実際、Ruby 1.9 より前のバージョンでは、何バイトしか表示されないため、さらに役に立ちません。)

String の 'en' 幅がいくつあるかを知りたいです。例えば:

'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

nStringの最初の en を取得できればさらに良いでしょう:

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

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

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

そして、全体を戦略化できればさらに良いでしょう。スペースは 0.25en にすべきだと考える人もいれば、0.33 にすべきだと考える人もいます。

4

6 に答える 6

5

ttfunk gem を使用して、フォント ファイルからメトリックを読み取ります。次に、テキスト文字列の幅を em 単位で取得できます。この例を gem に追加するためのプル リクエストを次に示します。

require 'rubygems'
require 'ttfunk'
require 'valuable'
# Everything you never wanted to know about glyphs:
# http://chanae.walon.org/pub/ttf/ttf_glyphs.htm

# this code is a substantial reworking of:
# https://github.com/prawnpdf/ttfunk/blob/master/examples/metrics.rb

class Font
  attr_reader :file

  def initialize(path_to_file)
    @file = TTFunk::File.open(path_to_file)
  end

  def width_of( string )
    string.split('').map{|char| character_width( char )}.inject{|sum, x| sum + x}
  end

  def character_width( character )
    width_in_units = ( horizontal_metrics.for( glyph_id( character )).advance_width )
    width_in_units.to_f / units_per_em
  end

  def units_per_em
    @u_per_em ||= file.header.units_per_em
  end

  def horizontal_metrics
    @hm = file.horizontal_metrics
  end

  def glyph_id(character)
    character_code = character.unpack("U*").first
    file.cmap.unicode.first[character_code]
  end
end

これが実際の動作です:

>> din = Font.new("#{File.dirname(__FILE__)}/../../fonts/DIN/DINPro-Light.ttf")
>> din.width_of("Hypertension")
=> 5.832
# which is correct! Hypertension in that font takes up about 5.832 em! It's over by maybe ... 0.015.
于 2015-02-25T17:24:23.220 に答える
4

標準化された「幅比率テーブル」を作成して近似を計算することもできます。基本的には、各文字の幅を保存してから、文字列をトラバースして幅を合計する必要があります。

私はこの表をここに見つけました:

Left, Width, Advance values for ArialBD16 'c' through 'm'
Letter  Left    Width   Advance
c        1       7       9
d        1       8       10
e        1       8       9
f        0       6       5
g        0       9       10
h        1       8       10
i        1       2       4
j       -1       4       4
k        1       8       9
l        1       2       4
m        1       12      14

真剣に取り組みたい場合は、webkit、gecko、および OO.org を調べることから始めますが、カーニングとサイズ計算のアルゴリズムは簡単ではないと思います。

于 2008-12-18T22:47:02.173 に答える
4

ImageMagick がインストールされている場合は、コマンド ラインからこの情報にアクセスできます。

$ convert xc: -font ./.fonts/HelveticaRoundedLTStd-Bd.otf  -pointsize 24 -debug annotate -annotate 0 'MyTestString' null: 2>&1
2010-11-02T19:17:48+00:00 0:00.010 0.010u 6.6.5 Annotate convert[22496]: annotate.c/RenderFreetype/1155/Annotate
  Font ./.fonts/HelveticaRoundedLTStd-Bd.otf; font-encoding none; text-encoding none; pointsize 24
2010-11-02T19:17:48+00:00 0:00.010 0.010u 6.6.5 Annotate convert[22496]: annotate.c/GetTypeMetrics/736/Annotate
  Metrics: text: MyTestString; width: 157; height: 29; ascent: 18; descent: -7; max advance: 24; bounds: 0,-5  20,17; origin: 158,0; pixels per em: 24,24; underline position: -1.5625; underline thickness: 0.78125
2010-11-02T19:17:48+00:00 0:00.010 0.010u 6.6.5 Annotate convert[22496]: annotate.c/RenderFreetype/1155/Annotate
  Font ./.fonts/HelveticaRoundedLTStd-Bd.otf; font-encoding none; text-encoding none; pointsize 24

Ruby から行うには、バッククォートを使用します。

result = `convert xc: -font #{path_to_font} -pointsize #{size} -debug annotate -annotate 0 '#{string}' null: 2>&1`
if result =~ /width: (\d+);/
  $1
end
于 2010-11-02T19:27:47.180 に答える
1

これは良い問題です!

私はSVG出力のためにルビーのpango/cairoを使用してそれを解決しようとしています。おそらく、pangoを使用して幅を計算してから、単純なsvg要素を使用します。

私は次のコードを使用します:

require "cairo"
require "pango"

paper = Cairo::Paper::A4_LANDSCAPE
TEXT = "Don't you love me anymore?"
def pac(surface)
        cr = Cairo::Context.new(surface)
        cr.select_font_face("Calibri",
                              Cairo::FONT_SLANT_NORMAL,
                              Cairo::FONT_WEIGHT_NORMAL)
    cr.set_font_size(12)
    extents = cr.text_extents(TEXT)
    puts extents
end

Cairo::ImageSurface.new(*paper.size("pt")) do |surface|
  cr = pac(surface)
end
于 2011-06-05T11:23:11.963 に答える