_text_layout.py 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. """
  2. Text layouting utilities.
  3. """
  4. from .ft2font import KERNING_DEFAULT, LOAD_NO_HINTING
  5. def layout(string, font, *, kern_mode=KERNING_DEFAULT):
  6. """
  7. Render *string* with *font*. For each character in *string*, yield a
  8. (glyph-index, x-position) pair. When such a pair is yielded, the font's
  9. glyph is set to the corresponding character.
  10. Parameters
  11. ----------
  12. string : str
  13. The string to be rendered.
  14. font : FT2Font
  15. The font.
  16. kern_mode : int
  17. A FreeType kerning mode.
  18. Yields
  19. ------
  20. glyph_index : int
  21. x_position : float
  22. """
  23. x = 0
  24. last_glyph_idx = None
  25. for char in string:
  26. glyph_idx = font.get_char_index(ord(char))
  27. kern = (font.get_kerning(last_glyph_idx, glyph_idx, kern_mode)
  28. if last_glyph_idx is not None else 0) / 64
  29. x += kern
  30. glyph = font.load_glyph(glyph_idx, flags=LOAD_NO_HINTING)
  31. yield glyph_idx, x
  32. x += glyph.linearHoriAdvance / 65536
  33. last_glyph_idx = glyph_idx