使用Python如何近似给定字符串的字体宽度?在
我正在寻找一个原型类似于:
def getApproximateFontWidth(the_string, font_name="Arial", font_size=12):
return ... picas or pixels or something similar ...
我不想找任何非常严格的东西,近似值就可以了。在
这样做的动机是我在我的webapp后端生成一个被截断的字符串,并将其发送到前端显示。大多数时候字符串都是小写的,但有时字符串都是大写的,这使得它们非常宽。如果这根绳子拉得不好,它看起来很难看。我想知道根据字符串的大致宽度截断多少。如果它降低了10%,那没什么大不了的,这是一个装饰性的功能。在
我使用了一个库来实现这一点,但是它需要pygame: http://inside.catlin.edu/site/compsci/ics/python/graphics.py 看看大小
您可以使用PIL呈现带有文本的图像,然后确定结果图像的宽度。在
http://effbot.org/imagingbook/imagefont.htm
下面是我的简单解决方案,它可以让你达到80%的准确率,非常适合我的目的。它只适用于Arial,它假定12磅字体,但它可能与其他字体成比例。在
如果你想截断一个字符串,这里是:
^{pr2}$然后是:
渲染时,这些字符串的宽度大致相同:
敏捷的棕色狐狸跳过
敏捷的棕色狐狸跳了起来
相关问题 更多 >
编程相关推荐