Skip to content Skip to sidebar Skip to footer

Roughly Approximate The Width Of A String Of Text In Python?

How would one, using Python, approximate the font width of a given string of text? I am looking for a function with a prototype similar to: def getApproximateFontWidth(the_string,

Solution 1:

Below is my simple solution, which gets you on the order of 80% accuracy, perfect for my purposes. It only works for Arial and it assumes 12 pt font, but it's probably proportional to other fonts as well.

defgetApproximateArialStringWidth(st):
    size = 0# in milinchesfor s in st:
        if s in'lij|\' ': size += 37elif s in'![]fI.,:;/\\t': size += 50elif s in'`-(){}r"': size += 60elif s in'*^zcsJkvxy': size += 85elif s in'aebdhnopqug#$L+<>=?_~FZT' + string.digits: size += 95elif s in'BSPEAKVXY&UwNRCHD': size += 112elif s in'QGOMm%W@': size += 135else: size += 50return size * 6 / 1000.0# Convert to picas

And if you want to truncate a string, here it is:

deftruncateToApproximateArialWidth(st, width):
    size = 0# 1000 = 1 inch
    width = width * 1000 / 6# Convert from picas to miliinchesfor i, s inenumerate(st):
        if s in'lij|\' ': size += 37elif s in'![]fI.,:;/\\t': size += 50elif s in'`-(){}r"': size += 60elif s in'*^zcsJkvxy': size += 85elif s in'aebdhnopqug#$L+<>=?_~FZT' + string.digits: size += 95elif s in'BSPEAKVXY&UwNRCHD': size += 112elif s in'QGOMm%W@': size += 135else: size += 50if size >= width:
            return st[:i+1]
    return st

Then the following:

>> width = 15>> print truncateToApproxArialWidth("the quick brown fox jumps over the lazy dog", width) 
the quick brown fox jumps over the
>> print truncateToApproxArialWidth("THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG", width) 
THE QUICK BROWN FOX JUMPS

When rendered, those strings are roughly the same width:

the quick brown fox jumps over the

THE QUICK BROWN FOX JUMPS

Solution 2:

You could render an image with the text using PIL and then determine the resulting image width.

http://effbot.org/imagingbook/imagefont.htm

Solution 3:

I have used a library that does this however it requires pygame: http://inside.catlin.edu/site/compsci/ics/python/graphics.py Look under sizeString

Post a Comment for "Roughly Approximate The Width Of A String Of Text In Python?"