用枕头将长绘制的文本分成多行 [英] Break long drawn text to multiple lines with Pillow

查看:72
本文介绍了用枕头将长绘制的文本分成多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个小的python程序,可以在128x48的小图像上绘制文本. 它仅适用于宽度为120的文本,但效果很好,但我不知道如何将较长的文本拆分为另一行.我该怎么做?

I'm creating a small python program that draws text on a small 128x48 image. It works fine for text that only reaches width of 120, but I can't figure out how to have longer text split into an additional line. How do I go about doing so?

我尝试使用textwrap3,但无法将其与Pillow配合使用.

I've attempted using textwrap3, but I couldn't get it to work with Pillow.

程序创建带有黑色背景和黄色居中文本的128x48图像文件,以后应在可输出480i的设备上查看,因此只需将文本缩小很多以使其适合其他文字宽度将无济于事.当前使用的字体是Arial 18.

The program creates 128x48 images files with a black background and yellow centered text, that is later supposed to be viewed on a device that outputs up to 480i, so simply making the text much smaller to fit additional text width won't be helpful. The font currently used is Arial 18.

以下是用于创建图片的当前代码:

Here's the current code used to create the image:

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')

上面的代码输出的图像是这样的:

The above code outputs the image like this:

宽度大于文本的长文本,则图像输出如下(LongerTextGoesHere):

Longer text with width bigger then the image outputs like this (LongerTextGoesHere):

所需结果应与此类似:

推荐答案

下面是一些使用PIL/Pillow二进制搜索功能将文本分成合适的代码的代码.

Here's some code that uses binary search with PIL/Pillow to break the text into pieces that fit.

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()

这篇关于用枕头将长绘制的文本分成多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆