1
0

このフォントは、固定ピッチフォントなのか?

Posted at

固定ピッチフォントか?

あやしぃ…。
実際のサイズを調べることにした。

描画サイズから固定ピッチかどうか判定してみる

is_monospace_font.py
import sys
from PIL import ImageFont, ImageDraw, Image

def is_monospace_font(font_path, test_string="iW"):
    try:
        # フォントサイズを指定してフォントオブジェクトを作成
        font = ImageFont.truetype(font_path, 40)

        # 描画用の領域を準備
        image = Image.new("RGB", (512, 512))
        draw = ImageDraw.Draw(image)

        # テストする文字列の各文字の幅を取得
        widths = [draw.textbbox((0, 0), char, font=font)[2] for char in test_string]

        # すべての文字の幅が同じかどうかを判定
        if len(set(widths)) == 1:
            return True
        else:
            print(widths)
            return False
    except Exception as e:
        print(f"エラーが発生しました: {e}")
        return False

if __name__ == "__main__":
    if len(sys.argv) < 2 or len(sys.argv) > 3:
        print("使用方法: python script_name.py <フォントのパス> [テスト文字列]")
        sys.exit(1)

    font_path = sys.argv[1]
    test_string = sys.argv[2] if len(sys.argv) == 3 else "iW"

    if is_monospace_font(font_path, test_string):
        print(f"このフォントは固定ピッチフォントです(テスト文字列: '{test_string}')。")
    else:
        print(f"このフォントはプロポーショナルフォントです(テスト文字列: '{test_string}')。")

使い方

調べたいフォントのファイルパスと文字幅を調べたい文字で判定します。

python is_monospace_font.py path/to/font_name.ttf " .1234567890"
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0