morfair
morfair

Reputation: 519

How to set font's kerning in Python Pillow?

For Pillow class ImageDraw (https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html#PIL.ImageDraw.PIL.ImageDraw.ImageDraw.text) I found param features. It can tune this font parameters: https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist

How to set kerning (kern) param? I don't know syntax.

This is not work:

draw.text((61, 386), text, (0, 0, 0), font=font, features={"kern": 1.0})

Upvotes: 3

Views: 4129

Answers (1)

Steven Woerpel
Steven Woerpel

Reputation: 71

I hit this same issue recently. I decided the best approach was to draw each letter individually and calculate the space between needed to make it even. This is the code I got it working with.

text = "Sample Text"
total_text_width, total_text_height = draw.textsize(text, font=font)
width_difference = desired_width_of_text - total_text_width
gap_width = int(width_difference / (len(text) - 1))
xpos = left_side_padding
for letter in text:
    draw.text((xpos,0),letter, (0,0,0), font=font)
    letter_width, letter_height = draw.textsize(letter, font=font)
    xpos += letter_width + gap_width
  • desired_width_of_text needs to be set and specifies the desired width of the text
  • left_side_padding should be 0 or specify any padding from the left side
  • font needs to specify a font in a suitable size

default spacing vs drawing each letter and calculating spacing

Upvotes: 5

Related Questions