Skip to content

Commit

Permalink
Merge pull request #24 from mustmodify/patch-1
Browse files Browse the repository at this point in the history
add example to get width of a string
  • Loading branch information
pointlessone authored Dec 12, 2023
2 parents 08ba10e + 0159ec8 commit 194f3cf
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions examples/character-or-string-width.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
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.

0 comments on commit 194f3cf

Please sign in to comment.