Skip to content

Instantly share code, notes, and snippets.

@rec
Created March 1, 2014 23:38
Show Gist options
  • Save rec/9299379 to your computer and use it in GitHub Desktop.
Save rec/9299379 to your computer and use it in GitHub Desktop.
Demonstration of issues with height of fonts gotten from PIL.
from __future__ import absolute_import, division, print_function, unicode_literals
"""
I'm trying to create fonts with a specific pixel height and then render them
into a box.
Unfortunately, the actual height of the font that's created is always somewhat
larger than the requested height. How do I create a font that has exactly the
right height?
"""
import sys
from PIL import Image, ImageDraw, ImageFont
TEXT = '||| ABCDEFGHIJKLMNOPQRSTUVWYZabcdefghijklmnopqrstuvwyz |||'
try:
FONT_FILE = sys.argv[1]
except:
FONT_FILE = 'DejaVuSansMono-Bold.ttf'
try:
HEIGHT = int(sys.argv[2])
except:
HEIGHT = 12
font = ImageFont.truetype(FONT_FILE, HEIGHT)
width, height = font.getsize(TEXT)
offset = font.getoffset(TEXT)
image = Image.new('RGBA', (width, height))
draw = ImageDraw.Draw(image)
draw.text((-offset[0], -offset[1]), text=TEXT, font=font)
image.show()
print('width=%d, height=%d, SLOP=%d' % (width, height, height - HEIGHT))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment