TTF字体表

Matplotlib支持FreeType字体。下面是一个使用‘table’命令构建字体表的小示例,该表按字符代码显示字形。

用法python font_table_ttf.py somefile.ttf

  1. import sys
  2. import os
  3. import matplotlib
  4. from matplotlib.ft2font import FT2Font
  5. from matplotlib.font_manager import FontProperties
  6. import matplotlib.pyplot as plt
  7. # the font table grid
  8. labelc = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  9. 'A', 'B', 'C', 'D', 'E', 'F']
  10. labelr = ['00', '10', '20', '30', '40', '50', '60', '70', '80', '90',
  11. 'A0', 'B0', 'C0', 'D0', 'E0', 'F0']
  12. if len(sys.argv) > 1:
  13. fontname = sys.argv[1]
  14. else:
  15. fontname = os.path.join(matplotlib.get_data_path(),
  16. 'fonts', 'ttf', 'DejaVuSans.ttf')
  17. font = FT2Font(fontname)
  18. codes = sorted(font.get_charmap().items())
  19. # a 16,16 array of character strings
  20. chars = [['' for c in range(16)] for r in range(16)]
  21. colors = [[(0.95, 0.95, 0.95) for c in range(16)] for r in range(16)]
  22. plt.figure(figsize=(8, 4), dpi=120)
  23. for ccode, glyphind in codes:
  24. if ccode >= 256:
  25. continue
  26. r, c = divmod(ccode, 16)
  27. s = chr(ccode)
  28. chars[r][c] = s
  29. lightgrn = (0.5, 0.8, 0.5)
  30. plt.title(fontname)
  31. tab = plt.table(cellText=chars,
  32. rowLabels=labelr,
  33. colLabels=labelc,
  34. rowColours=[lightgrn] * 16,
  35. colColours=[lightgrn] * 16,
  36. cellColours=colors,
  37. cellLoc='center',
  38. loc='upper left')
  39. for key, cell in tab.get_celld().items():
  40. row, col = key
  41. if row > 0 and col > 0:
  42. cell.set_text_props(fontproperties=FontProperties(fname=fontname))
  43. plt.axis('off')
  44. plt.show()

下载这个示例