1

I want to render a glyf of a TT-Font into an image (numpy.array):

from fontTools.ttLib import TTFont
import matplotlib.pyplot as plt

font = TTFont('font.ttf')
glyf = font['glyf']['A']
coords = np.array(glyf.coordinates)
coords = np.swapaxes(coords,0,1)
plt.scatter(coords[0], coords[1])

enter image description here

This are the vertices.

How can I draw the glyf to an numpy.array? I found glyf.draw(...) but I don't found a tutorial or examples how to use it. I also do not found any informations about the pen-concept.

Edit 1:

I found a way to render text with pillow:

from PIL import ImageFont, ImageDraw, Image

image = Image.new(mode='L', size=(128,128), color=224)
draw = ImageDraw.Draw(image)
imageFont = ImageFont.truetype('font.ttf', 64)
draw.text((0, 0), "A", font=imageFont)
image

enter image description here

That is a good start, but I need more control of the final result. There glyf shut be centered and in a size, that does use the space in a more efficient way.

I am also interested in the gridlines, f.ex. baseline and others.

Edit 2:

I found some hints in this question: How to get the font pixel height using PIL's ImageFont class?

from PIL import ImageFont, ImageDraw, Image

x_size = 128
y_size = 128

font_size = 64

imageFont = ImageFont.truetype('font.ttf', font_size)
ascent, descent = imageFont.getmetrics()

image = Image.new(mode='L', size=(x_size, y_size), color=224)
draw = ImageDraw.Draw(image)
text = 'Aj;^'

draw.line([0,ascent,127,ascent], fill=128)
draw.line([0,descent,127,descent], fill=128)

draw.text((0, 0), text, font=imageFont)
image

enter image description here

There are two lines that mark to points on the y-axis. But as you can see, there are characters going down one line. And characters are overlapping in the x-direction, as you can see on the "j" and "A".

I still need more control of the final result.

testo
  • 1,052
  • 2
  • 8
  • 24

0 Answers0