Rubygame::TTF - The difference between a string's width and the width of all it's characters

246 views Asked by At

I'm trying to use Rubygame to determine each of a string's character widths as a percentage of the string's total width...

require "rubygems"
require "rubygame"

include Rubygame

TTF.setup

$font = TTF.new "/Library/Fonts/Times New Roman.ttf", 40

total = 0

"Hello TrueType text! My name is Davide".each_char do |c|
  size = $font.size_text c

  #puts "Char: #{c} - #{size[0]}/#{total}"

  total = total + size[0]
end

puts "Size: #{$font.size_text('Hello TrueType text! My name is Davide')[0]}"
puts "Total: #{total}"
puts "Difference: #{total - $font.size_text('Hello TrueType text! My name is Davide')[0]}"

The program's output for the string above is...

Size: 642
Total: 650
Difference: 8

...And varies depending on the length and content of the string.

The result is close, but... Does anyone know why there's a difference of 8 between the sum of the character widths and the string's width?

Any help would be greatly appreciated...

Cheers...

Davide

PS I'm also open to suggestions about other/better ways of doing this.

1

There are 1 answers

0
Daniel Pittman On BEST ANSWER

The result is close, but... Does anyone know why there's a difference of 8 between the sum of the character widths and the string's width?

Yes: because a good TrueType font, like any good font, will be kerned by the layout engine. http://en.wikipedia.org/wiki/Kerning

When doing layout with variable width fonts - which you want - always use the full string width. Per-character numbers are meaningless. (...and, really, the "right" way to do this is to use something that does layout for you. Pango is a project that does that; go count the lines of code, and consider if you really want to write that yourself.)