Guy*_*wig 3 python python-imaging-library
我正在创建一个小型 python 程序,用于在 128x48 的小图像上绘制文本。它适用于宽度仅达到 120 的文本,但我不知道如何将较长的文本拆分为额外的行。我该怎么做呢?
我尝试使用 textwrap3,但无法让它与 Pillow 一起使用。
该程序创建具有黑色背景和黄色居中文本的 128x48 图像文件,稍后应该在输出高达 480i 的设备上查看该文件,因此简单地使文本小得多以适应额外的文本宽度是没有帮助的。目前使用的字体是Arial 18。
这是用于创建图像的当前代码:
from PIL import Image, ImageDraw, ImageFont
AppName = "TextGoesHere"
Font = ImageFont.truetype('./assets/Arial.ttf', 18)
img = Image.new('RGB', (128, 48), color='black')
d = ImageDraw.Draw(img)
# Get width and height of text
w, h = d.textsize(AppName, font=Font)
# Draw text
d.text(((128-w)/2, (48-h)/2), AppName, font=Font, fill=(255, 255, 0))
img.save('icon.png')
Run Code Online (Sandbox Code Playgroud)
上面的代码输出的图像如下:
![]()
宽度大于图像的较长文本输出如下(LongerTextGoesHere):
![]()
想要的结果应该与此类似:
![]()
下面是一些代码,使用 PIL/Pillow 的二分搜索将文本分解成合适的片段。
def break_fix(text, width, font, draw):
if not text:
return
lo = 0
hi = len(text)
while lo < hi:
mid = (lo + hi + 1) // 2
t = text[:mid]
w, h = draw.textsize(t, font=font)
if w <= width:
lo = mid
else:
hi = mid - 1
t = text[:lo]
w, h = draw.textsize(t, font=font)
yield t, w, h
yield from break_fix(text[lo:], width, font, draw)
def fit_text(img, text, color, font):
width = img.size[0] - 2
draw = ImageDraw.Draw(img)
pieces = list(break_fix(text, width, font, draw))
height = sum(p[2] for p in pieces)
if height > img.size[1]:
raise ValueError("text doesn't fit")
y = (img.size[1] - height) // 2
for t, w, h in pieces:
x = (img.size[0] - w) // 2
draw.text((x, y), t, font=font, fill=color)
y += h
img = Image.new('RGB', (128, 48), color='black')
fit_text(img, 'LongerTextGoesHere', (255,255,0), Font)
img.show()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3207 次 |
| 最近记录: |