Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw underline text with PIL

There is a post related to bold/italic: Draw bold/italic text with PIL?

However, how to draw underline text with PIL?

like image 262
lucemia Avatar asked Jan 15 '12 08:01

lucemia


1 Answers

Looks like there is no standard way of doing this, but you always can implement it.

Possible solution:

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()
like image 139
reclosedev Avatar answered Oct 10 '22 19:10

reclosedev