粗略接近Python中一串文本的宽度?

spe*_*ane 6 python fonts

如何使用Python来近似给定文本字符串的字体宽度?

我正在寻找一个类似于以下原型的函数:

def getApproximateFontWidth(the_string, font_name="Arial", font_size=12):
   return ... picas or pixels or something similar ...
Run Code Online (Sandbox Code Playgroud)

我不是在寻找任何非常严谨的东西,近似会很好.

这样做的动机是我在webapp的后端生成一个截断的字符串并将其发送到前端进行显示.大多数情况下琴弦是小写的,但有时琴弦全部都是大写的,因此它们非常宽.如果字符串没有正确分组,它看起来很难看.我想知道基于它们的近似宽度来截断字符串的程度.如果它关闭了10%这不是什么大问题,这是一个美容功能.

spe*_*ane 8

以下是我的简单解决方案,它可以让您达到80%的准确度,非常适合我的目的.它仅适用于Arial并且它采用12磅字体,但它也可能与其他字体成比例.

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

如果你想截断一个字符串,这里是:

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

然后是以下内容:

>> 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
Run Code Online (Sandbox Code Playgroud)

渲染时,这些字符串的宽度大致相同:

快速的棕色狐狸跳过了

快速的棕色狐狸跳

  • 为什么这比PIL的`font.getsize('spam')更好? (2认同)