[英]Creating a multiline text using PIL
所以我知道這里有一個與此有些類似的問題,但是我的不同。 所以我有這段代碼定義了字體、圖像、文本和最大文本寬度:
from PIL import Image, ImageFont
texts = ['This is a test', 'Message that is very long and should exceed 250 pixels in terms of width']
bg = Image.open(f"data/background.png")
font = ImageFont.truetype(f"data/minecraft-font.ttf", 16)
text_width = font.getsize(texts[1])[0]
if text_width > 250:
# return a list that has the lines
基本上它應該返回這樣的東西
lines = ['Message that is very long','and should exceed 250 pixels in','terms of width']
我試着自己做……但結果是一團糟。 我最初的計划是不斷地從字符串中刪除單詞並將刪除的單詞放在另一個字符串中,但結果很糟糕。 任何人都可以幫忙嗎?
更新:v25 所說的讓我明白:
import requests
from PIL import ImageFont, Image, ImageOps, ImageDraw
import textwrap
offset = margin = 60
bg = Image.open('data/background.png').resize((1000,1000))
font = ImageFont.truetype(f"data/minecraft-font.ttf", 16)
text = 'Hello my name is beep boop and i am working on a bot called testing bot 123'
draw = ImageDraw.Draw(bg)
for line in textwrap.wrap(text, width=2500):
draw.text((offset,margin), line, font=font, fill="#aa0000")
offset += font.getsize(line)[1]
bg.save('text.png')
您已將寬度設置為 2500,但text
只有 75 個字符長,因此這僅在圖像中生成一行。 嘗試使用width=24
進行測試,結果列表應包含 4 個項目:
['Hello my name is beep', 'boop and i am working on', 'a bot called testing bot', '123']
您也可以避免在 for 循環中調用draw.text
,因為它接受一個帶有換行符的字符串作為第二個參數。
所以簡單的像:
text = 'Hello my name is beep boop and i am working on a bot called testing bot 123'
textwrapped = textwrap.wrap(text, width=24)
draw.text((offset,margin), '\n'.join(textwarpped), font=font, fill="#aa0000")
當然,您隨后需要查看它如何渲染並相應地為您的背景圖像調整寬度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.