スポンサーリンク

FreeType2で異体字を描画する

あるフォントの、指定した文字の異体字一覧を取得するにはFT_Face_GetVariantsOfCharを使う。この関数を使うとフォントが対応している異体字セレクタの一覧を取得できる。

フォント+異体字の情報があれば、FT_Face_GetCharVariantIndexでグリフインデクスを取得できる。あとはFT_Load_Glyphすればよい。

#include <vector>

#include <ft2build.h>
#include FT_FREETYPE_H

#include <freetype/ftstroke.h>

#pragma warning(disable:4996)

#pragma comment(lib,"freetype.lib")

#include <bitset>

int main()
{

    FT_Library  library; // handle to library
    FT_Error error;

    error = FT_Init_FreeType(&library);
    if (error)
        return -1;

    FT_Face face;      // handle to face object

    //msgothic.ttc
    //meiryo.ttc
    // フォントファイル読み込み
    error = FT_New_Face(
        library,
        "C:\\Windows\\Fonts\\msgothic.ttc",
        0,
        &face
    );

    //文字コード指定
    error = FT_Select_Charmap(
        face,               // target face object
        FT_ENCODING_UNICODE // エンコード指定
    );


    if (error == FT_Err_Unknown_File_Format)
        return -1;
    else if (error)
        return -1;

    int pixel_heigth = 255;

    //この二つの値でフォントサイズ調整
    FT_Set_Pixel_Sizes(
        face,          // handle to face object
        0,             // pixel_width  
        pixel_heigth   // pixel_height
    );

    /////////////////////////////
    // 文字の取得
    FT_ULong character = wchar_t(L'辻');


      
    /////////////////////////////
    // 異体字セレクタの一覧を取得
    FT_UInt32* list = FT_Face_GetVariantsOfChar(face, character);
    int ivs_count = 0;

    // 異体字セレクタの一覧を表示・個数カウント
    for (FT_UInt32* li = list; *li != 0; li++) {
        printf("%x", *list);
        ivs_count++;
    }

    // 異体字を使わないなら0にする
    // ivs_count = 0;

    FT_UInt char_index;
    if (ivs_count != 0) {
// 文字コードと異体字セレクタからグリフインデクス取得
char_index = FT_Face_GetCharVariantIndex(face, character, list[0]); } else{ //異体字が一つもない時は普通のグリフインデクス取得 char_index = FT_Get_Char_Index(face, character); }
    
      
    // グリフ(字の形状)読込
    error = FT_Load_Glyph(face, char_index, FT_LOAD_DEFAULT/*FT_LOAD_RENDER*/);
    if (error)
        return -1; // ignore errors

    // 文字を画像化
    FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL);


    int Width = face->glyph->bitmap.width;
    int Height = face->glyph->bitmap.rows;
    ////////////////////////////////////////
    ////////////////////////////////////////
    // ファイル出力
    FILE* fp = fopen("C:\\test\\freetypetest.pbm", "wb");
    fprintf(fp, "P2\n%d %d\n255\n", Width, Height);
    for (int i = 0; i < Width*Height;i++) {
        fprintf(fp, "%d ", face->glyph->bitmap.buffer[i]);
    }
    fclose(fp);
    ////////////////////////////////////////
    ////////////////////////////////////////

    // FreeType2の解放
    FT_Done_Face(face);
    FT_Done_FreeType(library);
}

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)


この記事のトラックバックURL: