大概相当于Python中一个文本字符串的宽度?

2024-10-03 11:20:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我正在寻找一个原型类似于:

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

我不想找任何非常严格的东西,近似值就可以了。在

这样做的动机是我在我的webapp后端生成一个被截断的字符串,并将其发送到前端显示。大多数时候字符串都是小写的,但有时字符串都是大写的,这使得它们非常宽。如果这根绳子拉得不好,它看起来很难看。我想知道根据字符串的大致宽度截断多少。如果它降低了10%,那没什么大不了的,这是一个装饰性的功能。在


Tags: orthe字符串namesizestringreturn宽度
3条回答

我使用了一个库来实现这一点,但是它需要pygame: http://inside.catlin.edu/site/compsci/ics/python/graphics.py 看看大小

您可以使用PIL呈现带有文本的图像,然后确定结果图像的宽度。在

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

下面是我的简单解决方案,它可以让你达到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

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

^{pr2}$

然后是:

>> 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

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

敏捷的棕色狐狸跳过

敏捷的棕色狐狸跳了起来

相关问题 更多 >