Skip to content

Instantly share code, notes, and snippets.

@petrblahos
Created October 19, 2023 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petrblahos/a60f56db79afefedb7e0da950fb2e758 to your computer and use it in GitHub Desktop.
Save petrblahos/a60f56db79afefedb7e0da950fb2e758 to your computer and use it in GitHub Desktop.
Draw a character from a ttf font using fonttools / pen.
import wx
from fontTools.pens.wxPen import WxPen
from fontTools.ttLib import TTFont
class MyFrame(wx.Frame):
def __init__(self, ttfont: TTFont):
wx.Frame.__init__(self, None, -1, "Font painter")
self.font = ttfont
self.Bind(wx.EVT_PAINT, self.on_paint)
def on_paint(self, evt):
evt.Skip()
height = self.GetSize()[1]
units_per_em = self.font['head'].unitsPerEm
scale = height / 4 / units_per_em
dc = wx.PaintDC(self)
gc = wx.GraphicsContext.Create(dc)
glyph = self.font.getGlyphSet()['A']
pen = WxPen(self.font.getGlyphSet())
glyph.draw(pen)
m = gc.CreateMatrix()
# Move to the vertical centre of the window
m.Translate(0, height // 2)
# Flip the y axis
m.Scale(scale, -scale)
pen.path.Transform(m)
gc.SetBrush(wx.BLACK_BRUSH)
gc.FillPath(pen.path)
def show_ui(font):
app = wx.App()
frame = MyFrame(font)
frame.Show()
frame.Maximize(True)
app.MainLoop()
if "__main__" == __name__:
show_ui(TTFont("Roboto-Regular.ttf"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment