根据字符宽度将字符串分成多行(python) [英] Breaking string into multiple lines according to character width (python)
问题描述
我正在通过 PIL
在基本图像上绘制文本.一个要求是如果所有字符的组合宽度超过基本图像的宽度,它就会溢出到下一行.
I am drawing text atop a base image via PIL
. One of the requirements is for it to overflow to the next line(s) if the combined width of all characters exceeds the width of the base image.
目前我正在使用 textwrap.wrap(text, width=16)
来实现这一点.这里 width
定义了一行中容纳的字符数.现在文本可以是任何内容,因为它是用户生成的.所以问题是硬编码 width
不会考虑 width
由于字体类型、字体大小和字符选择而产生的可变性.
Currently I'm using textwrap.wrap(text, width=16)
to accomplish this. Here width
defines the number of characters to accommodate in one line. Now the text can be anything since it's user generated. So the problem is that hard-coding width
won't take into account width
variability due to font type, font size and character selection.
我是什么意思?
好吧,想象一下我正在使用 DejaVuSans.ttf
,大小为 14.W
的长度为 14,而i"的长度为 4.对于基本图像宽度为 400,单行最多可容纳 100 个 i
字符.但只有 29 个 W
字符.我需要制定一种更智能的换行方式,当字符宽度的总和超过基本图像宽度时,字符串会断开.
Well imagine I'm using DejaVuSans.ttf
, size 14. A W
is 14 in length, whereas an 'i' is 4. For a base image of width 400, up to 100 i
characters can be accommodated in a single line. But only 29 W
characters. I need to formulate a smarter way of wrapping to the next line, one where the string is broken when the sum of character-widths exceeds the base image width.
有人可以帮我制定这个吗?一个说明性的例子会很棒!
Can someone help me formulate this? An illustrative example would be great!
推荐答案
既然你知道每个字符的宽度,你应该把它做成一个字典,从中得到宽度来计算字符串宽度:
Since you know the width of each character, you should make that into a dictionary, from which you get the widths to calculate the stringwidth:
char_widths = {
'a': 9,
'b': 11,
'c': 13,
# ...and so on
}
从这里您可以查找每个字母并使用该总和来检查您的宽度:
From here you can lookup each letter and use that sum to check your width:
current_width = sum([char_widths[letter] for letter in word])
这篇关于根据字符宽度将字符串分成多行(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!