使用PIL绘制下划线文本

时间:2012-01-15 08:56:50

标签: python python-imaging-library underline

有一篇与粗体/斜体有关的帖子: Draw bold/italic text with PIL?

但是,如何使用PIL绘制下划线文本?

1 个答案:

答案 0 :(得分:4)

看起来没有标准的方法可以做到这一点,但你总能实现它。

可能的解决方案:

import Image
import ImageDraw
import ImageFont

def draw_underlined_text(draw, pos, text, font, **options):    
    twidth, theight = draw.textsize(text, font=font)
    lx, ly = pos[0], pos[1] + theight
    draw.text(pos, text, font=font, **options)
    draw.line((lx, ly, lx + twidth, ly), **options)

im = Image.new('RGB', (400, 400), (255,)*3)
draw = ImageDraw.Draw(im)
font = ImageFont.truetype("arial.ttf", 50)

draw_underlined_text(draw, (50, 150), 'Hello PIL!', font, fill=0)
draw_underlined_text(draw, (50, 300), 'Test', font, fill=128)

im.show()