Draw a font table
In this step, we will define a function draw_font_table
that draws a font table of the first 255 characters of the given font.
import os
from pathlib import Path
import unicodedata
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from matplotlib.ft2font import FT2Font
def draw_font_table(path):
"""
Draw a font table of the first 255 chars of the given font.
Parameters
----------
path : str or None
The path to the font file. If None, use Matplotlib's default font.
"""
if path is None:
path = fm.findfont(fm.FontProperties()) ## The default font.
font = FT2Font(path)
## Get the charmap of the font
codes = font.get_charmap().items()
## Create the labels and cells of the table
labelc = [f"{i:X}" for i in range(16)]
labelr = [f"{i:02X}" for i in range(0, 16*16, 16)]
chars = [["" for c in range(16)] for r in range(16)]
for char_code, glyph_index in codes:
if char_code >= 256:
continue
row, col = divmod(char_code, 16)
chars[row][col] = chr(char_code)
## Draw the table using Matplotlib's Axes.table
fig, ax = plt.subplots(figsize=(8, 4))
ax.set_title(os.path.basename(path))
ax.set_axis_off()
table = ax.table(
cellText=chars,
rowLabels=labelr,
colLabels=labelc,
rowColours=["palegreen"] * 16,
colColours=["palegreen"] * 16,
cellColours=[[".95" for c in range(16)] for r in range(16)],
cellLoc='center',
loc='upper left',
)
## Set the font of the table cells to the font of the given path
for key, cell in table.get_celld().items():
row, col = key
if row > 0 and col > -1: ## Beware of table's idiosyncratic indexing...
cell.set_text_props(font=Path(path))
fig.tight_layout()
plt.show()