Center-/middle-align text with PIL?

后端 未结 5 1016
长情又很酷
长情又很酷 2020-12-04 07:50

How would I center-align (and middle-vertical-align) text when using PIL?

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 08:03

    Here is some example code which uses textwrap to split a long line into pieces, and then uses the textsize method to compute the positions.

    from PIL import Image, ImageDraw, ImageFont
    import textwrap
    
    astr = '''The rain in Spain falls mainly on the plains.'''
    para = textwrap.wrap(astr, width=15)
    
    MAX_W, MAX_H = 200, 200
    im = Image.new('RGB', (MAX_W, MAX_H), (0, 0, 0, 0))
    draw = ImageDraw.Draw(im)
    font = ImageFont.truetype(
        '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', 18)
    
    current_h, pad = 50, 10
    for line in para:
        w, h = draw.textsize(line, font=font)
        draw.text(((MAX_W - w) / 2, current_h), line, font=font)
        current_h += h + pad
    
    im.save('test.png')
    

    enter image description here

提交回复
热议问题