Center-/middle-align text with PIL?

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

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

5条回答
  •  失恋的感觉
    2020-12-04 08:15

    Use Draw.textsize method to calculate text size and re-calculate position accordingly.

    Here is an example:

    from PIL import Image, ImageDraw
    
    W, H = (300,200)
    msg = "hello"
    
    im = Image.new("RGBA",(W,H),"yellow")
    draw = ImageDraw.Draw(im)
    w, h = draw.textsize(msg)
    draw.text(((W-w)/2,(H-h)/2), msg, fill="black")
    
    im.save("hello.png", "PNG")
    

    and the result:

    If your fontsize is different, include the font like this:

    myFont = ImageFont.truetype("my-font.ttf", 16)
    draw.textsize(msg, font=myFont)
    

提交回复
热议问题