Created
March 1, 2014 23:38
-
-
Save rec/9299379 to your computer and use it in GitHub Desktop.
Demonstration of issues with height of fonts gotten from PIL.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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