FreeType2是一個簡單的跨平台的字型繪製引擎.目前支援TrueType Type1 Type2等字型格式.不過目前好象還不支援OpenType. 使用FreeType的應用很多.著名的FTGL就是使用FreeType的.能在OpenGL高效率的繪製向量字型. FTGL我沒用過.因為不想在沒瞭解該怎麼用FreeType的情況下就去用FTGL. 經過一個晚上的閱讀代碼(My Code閱讀能力是很差的).終於知道了如何使用FreeType2了。不過是簡單的使用,還不知道如何設定Bold Itainly等屬性.主要是簡單的示範.以後準備做成一個完善的字型引擎. 下面簡單的介紹一下. 首先當然是包含標頭檔了。標頭檔要這樣包含: #include [ft2build.h] #include FT_FREETYPE_H 不知道為什麼.反正就是要這麼包含. 以下為FT2的初始化代碼.和繪製以及釋放的代碼> 注意這裡繪製代碼接受的字元是Unicode.表示你這樣舊可以繪製了 FT2_Obj font; font.Init("SimSun.ttf",32); wchat_t pText[]=L"潘李亮是一頭野豬"; for(int n = 0 ; n< wcslen(pText);n++) { font.DrawAUnicode(pText[n]; } font.Free(); //以下為FT2_Obj的代碼. //主要參考了Nehe的Lesson 43 class FT2_Obj { FT_Library library; int h ; FT_Face face; public: void Init(const char * fname, unsigned int h); void Free(); void DrawAUnicode(wchar_t ch) }; void FT2_Obj::Init(const char * fname, unsigned int h) { this->h=h; //初始化FreeType庫.. if (FT_Init_FreeType( &library )) throw std::runtime_error("FT_Init_FreeType failed"); //載入一個字型,取預設的Face,一般為Regualer if (FT_New_Face( library, fname, 0, &face )) throw std::runtime_error("FT_New_Face failed (there is probably a problem with your font file)"); //大小要乘64.這是規定。照做就可以了。 FT_Set_Char_Size( face,h<< 6, h << 6, 96, 96); FT_Matrix matrix; /* transformation matrix */ FT_UInt glyph_index; FT_Vector pen; //給它設定個旋轉矩陣 float angle = -20/180.* 3.14; matrix.xx = (FT_Fixed)( cos( angle ) * 0x10000L ); matrix.xy = (FT_Fixed)(-sin( angle ) * 0x10000L ); matrix.yx = (FT_Fixed)( sin( angle ) * 0x10000L ); matrix.yy = (FT_Fixed)( cos( angle ) * 0x10000L ); FT_Set_Transform( face, &matrix, &pen ); }. void FT2_Obj::DrawAUnicode(wchar_t ch) { if(FT_Load_Glyph( face, FT_Get_Char_Index( face, ch ), FT_LOAD_DEFAULT )) throw std::runtime_error("FT_Load_Glyph failed"); //得到字模 FT_Glyph glyph; if(FT_Get_Glyph( face->glyph, &glyph )) throw std::runtime_error("FT_Get_Glyph failed"); //轉化成位元影像 FT_Render_Glyph( face->glyph, FT_RENDER_MODE_NORMAL ); FT_Glyph_To_Bitmap( &glyph, ft_render_mode_normal, 0, 1 ); FT_BitmapGlyph bitmap_glyph = (FT_BitmapGlyph)glyph; //取道位元影像資料 FT_Bitmap& bitmap=bitmap_glyph->bitmap; //把位元影像資料拷貝自己定義的資料區裡.這樣舊可以畫到需要的東西上面了。 int width = bitmap.width; int height = bitmap.rows; usigned char* expanded_data = new usigned char[ 3 * width * height]; for(int j=0; j <height;j++) { for(int i=0; i < width; i++) { expanded_data[3*(i+(height-j-1)*width)]= expanded_data[3*(i+(height-j-1)*width)+1] = expanded_data[3*(i+(height-j-1)*width)+2] = (i>=bitmap.width || j>=bitmap.rows) ? 0 : bitmap.buffer[i + bitmap.width*j]; } } /* 繪製操作. */ } void FT2_Obj::Free() { FT_Done_Face(face); FT_Done_FreeType(library); } |