Skip to content

Instantly share code, notes, and snippets.

@timrprobocom
Created February 25, 2022 23:27
Show Gist options
  • Save timrprobocom/d1de6ac955af7003e7abd2ca8e72955c to your computer and use it in GitHub Desktop.
Save timrprobocom/d1de6ac955af7003e7abd2ca8e72955c to your computer and use it in GitHub Desktop.
How to draw text in boxes
from PIL import ImageDraw, Image, ImageFont
BLACK = (0,0,0)
WHITE = (255,255,255)
LTBLUE = (192,192,255)
fig = Image.new( "RGB", (320,320), WHITE )
arial = ImageFont.truetype("../.fonts/arial.ttf", 32 )
y = 100
def drawboxstring( img, s, y ):
xleft = (fig.width - 50*len(s)) // 2
d = ImageDraw.Draw(img)
for c in s:
d.rectangle( ((xleft, y), (xleft+50,y+50)), outline=BLACK, fill=LTBLUE )
d.text( (xleft+12, y+10), c, font=arial, fill=BLACK )
xleft += 50
drawboxstring( fig, "AB", y )
y += 50
drawboxstring( fig, "CDE", y )
y += 50
drawboxstring( fig, "FGHI", y )
fig.save( "abc.png" )
@timrprobocom
Copy link
Author

Here's the output:
abc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment