python - 用文字完美填充图像
问题描述
我想创建一个带有 PILLOW 的图像,其中填充了文本。
我不知道如何设置完美的行数和字体大小来做到这一点。
这是我需要的渲染示例:
我正在处理的代码:
from PIL import Image, ImageDraw, ImageFont
import textwrap
def draw_multiple_line_text(image, text, font, text_color, text_start_height):
draw = ImageDraw.Draw(image)
image_width, image_height = image.size
y_text = text_start_height
lines = textwrap.wrap(text, width=60)
for line in lines:
line_width, line_height = font.getsize(line)
print(line_width, line_height)
draw.text(((image_width - line_width) / 2, y_text), line, font=font, fill=text_color)
y_text += line_height
def main():
image = Image.new('RGB', (500, 500), color=(0, 0, 0))
fontsize = 20 # starting font size
font = ImageFont.truetype("arial.ttf", fontsize)
text = "No, woman, no cry No, woman, no cry No, woman, no cry No, woman, no cry 'Cause, 'cause, 'cause I remember when we used to sit In the government yard in Trenchtown Oba observing the 'ypocrites Mingle with the good people we meet Good friends we have, oh, good friends we've lost Along the way In this great future, you can't forget your past So dry your tears, I seh No, woman, no cry No, woman, no cry 'Ere, little darlin', don't shed no tears No, woman, no cry Said, said, said, I remember when-a we used to sit In the government yard in Trenchtown And then Georgie would make the fire lights, I seh A log wood burnin' through the night Then we would cook cornmeal porridge, I seh Of which I'll share with you My feet is my only carriage And so I've got to push on through… "
text_color = (200, 200, 200)
text_start_height = 0
draw_multiple_line_text(image, text, font, text_color, text_start_height)
image.save('pil_text.png')
if __name__ == "__main__":
main()
当前渲染:
预先感谢您的帮助。
解决方案
这不是字体和大小的问题;事实上,对于大多数文本,这些选择不足以提供完美的填充。
仔细查看目标文本:完美来自在每行的单词之间插入适当的空格。你必须仔细阅读文本,尽可能地填写每一行。一旦确定了换行符所属的位置,就进行第二次遍历,根据需要分配空格以将最右边的字符扩展到右边距。
为此,您计算不足,将其除以单位空间的宽度(这与字体不同),然后将这些空间均匀地分配到文本中的现有空间。“均匀”是您选择的过程。
推荐阅读
- java - 如何使用 ParameterizedTest 中的参数的嵌套属性定义显示名称(name = #{index} multiply {0[0]} x {0[1]} = {0[2]})
- django - AWS Lightsail 上未提供静态文件
- reactjs - 无法从 sqlite 在 react usestate 数组中设置记录
- c# - 如何在c#中有效地比较两个十进制值
- java - 使用 LambdaMetafactory 线程进行动态方法调用是否安全?
- azure-iot-hub - 使用按记录分组的最后 5 条记录的多维数组调用 Azure 流分析 UDF
- firebase - 如何在 Flutter 中从 Firebase 存储中获取相关图像
- javascript - 默认值作为国际化字符串是否会使组件不纯?
- php - 将 file.php 重命名为自定义单词
- ms-access - 具有多个条件的 Dlookup 返回相同的结果