0

I'm making a command line version of shields.io for fun, so no browser/v8 engine. I have most of the program nailed down but given a string I cannot determine how long, in pixels, it will end up on the screen, and thus adjust my background. My current solution is just to get sum of the width of every character in my string (precalculated from a js script I ran in a browser). But when you add special characters and the fact that different letter combinations have different spacing in between I usually end up with shields that are either too big or too small.

So I'm looking for the algorithm that, given a font family, returns the width of the string.

Pyves
  • 6,333
  • 7
  • 41
  • 59
  • You might find the answer to this question of help... http://stackoverflow.com/questions/22904372/how-do-i-calculate-the-space-in-between-two-glyphs-in-a-ttf-font – Holger Will Oct 04 '16 at 03:49

2 Answers2

0

So I found a solution that worked for me. I'm using golang and there's already a ttf library, so I loaded the dejavu-sans font and calculated the width with the help of the library.

0

I did this using approximation based on a font width and a percentage width based the character. This code is in Python, but easily transferrable:

    # A dictionary containing percentages that relate to how wide
    # each character will be represented in a variable width font.
    char_width_percentages = {
        "lij|' ": 40.0,
        '![]fI.,:;/\\t': 50.0,
        '`-(){}r"': 60.0,
        '*^zcsJkvxy': 70.0,
        'aebdhnopqug#$L+<>=?_~FZT0123456789': 70.0,
        'BSPEAKVXY&UwNRCHD': 70.0,
        'QGOMm%W@': 100.0
    }

My code is here, and is incidentally also for a command-line badge generation tool.

JGC
  • 5,725
  • 1
  • 32
  • 30