我目前正在使用一个输出带有文本的图像的 Python 机器人,但我发现文本通常太长而无法显示。因此,我决定将字符串分成两行,以便它适合我的图像。我正在使用 Pillow 5.1 进行图像处理。
我是 Python 编程的新手,我试图搜索如何将 Python 字符串分成两行或更多行。不幸的是,所有的结果似乎只处理显式给出的字符串(即“字符串”)。
print("Ababoubian wisdom!")
ababou2 = ababou() #returns a string, how to split into two lines?
if("Ababou" in ababou2):
ababou2 = ababou()
font = ImageFont.truetype("Arial.ttf", 14)
img = Image.new('RGB', (300, 200), color = (random.randint(0, 255),random.randint(0, 255), random.randint(0, 255)))
d = ImageDraw.Draw(img)
d.text((0, 0), ababou2, font=font) #draws text
预期结果:文本应该环绕到下一行。
我不确定文本包装器是否可以帮助您,因为您需要单独绘制每条线。
似乎您应该在一行中计算字符的最大长度,然后执行以下操作:
ababou2 = ababou() # Whats the point of assigning the same value twice?
# does ababou() returns a different value each time?
if "Ababou" in ababou2:
ababou2 = ababou()
res_text = list()
ababou2 = ababou2.split(' ') # Splits the string by space\ ' ', to a list of strings
curr_txt = ''
for word in ababou2:
if len(curr_txt) < MAX_CHARS_PER_LINE: # This you need to figure out
curr_txt += ' ' + word
else:
res_text.append(curr_txt)
curr_txt = word
font = ImageFont.truetype("Arial.ttf", 14)
img = Image.new('RGB', (300, 200), color = (random.randint(0, 255),random.randint(0, 255), random.randint(0, 255)))
d = ImageDraw.Draw(img)
y = 0
for line in res_text:
d.text((0, y), line, font=font) #draws text
y += SINGLE_ROW_SPACE # Figure out what is the distance between two rows.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句