Matplotlib 로 폰트 테이블 그리기

Beginner

This tutorial is from open-source community. Access the source code

소개

Matplotlib 는 Python 에서 널리 사용되는 데이터 시각화 라이브러리입니다. FreeType 라이브러리를 통해 폰트 지원을 제공합니다. 이 랩에서는 Matplotlib 의 Axes.table을 사용하여 주어진 폰트의 처음 255 개 문자에 대한 폰트 테이블을 그리는 방법을 배웁니다.

VM 팁

VM 시작이 완료되면 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 액세스하십시오.

때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한 사항으로 인해 작업의 유효성 검사를 자동화할 수 없습니다.

학습 중에 문제가 발생하면 언제든지 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 신속하게 해결해 드리겠습니다.

폰트의 글리프 출력

이 단계에서는 주어진 폰트 파일의 모든 글리프를 stdout 으로 출력하는 함수 print_glyphs를 정의합니다.

import os
import unicodedata
import matplotlib.font_manager as fm
from matplotlib.ft2font import FT2Font

def print_glyphs(path):
    """
    Print the all glyphs in the given font file to stdout.

    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)

    charmap = font.get_charmap()
    max_indices_len = len(str(max(charmap.values())))

    print("The font face contains the following glyphs:")
    for char_code, glyph_index in charmap.items():
        char = chr(char_code)
        name = unicodedata.name(
                char,
                f"{char_code:#x} ({font.get_glyph_name(glyph_index)})")
        print(f"{glyph_index:>{max_indices_len}} {char} {name}")

폰트 테이블 그리기

이 단계에서는 주어진 폰트의 처음 255 개 문자에 대한 폰트 테이블을 그리는 함수 draw_font_table을 정의합니다.

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()

폰트 테이블 표시

이 단계에서는 argparse를 사용하여 명령줄 인자에서 폰트 파일의 경로를 파싱합니다. 그런 다음 print_glyphs를 호출하여 폰트 파일의 모든 글리프를 출력하고, draw_font_table을 호출하여 폰트의 처음 255 개 문자에 대한 폰트 테이블을 그립니다.

if __name__ == "__main__":
    from argparse import ArgumentParser

    parser = ArgumentParser(description="Display a font table.")
    parser.add_argument("path", nargs="?", help="Path to the font file.")
    parser.add_argument("--print-all", action="store_true",
                        help="Additionally, print all chars to stdout.")
    args = parser.parse_args()

    if args.print_all:
        print_glyphs(args.path)
    draw_font_table(args.path)

요약

이 랩에서는 Matplotlib 의 Axes.table을 사용하여 폰트 파일의 처음 255 개 문자에 대한 폰트 테이블을 그리는 방법을 배웠습니다. 폰트 파일의 모든 글리프를 출력하고 폰트 테이블을 그리는 함수를 정의했습니다. 또한 argparse를 사용하여 명령줄 인자에서 폰트 파일의 경로를 파싱했습니다.