2012-05-10 21 views
7

我聽說fontconfig是在linux中獲取字體的最佳選擇。不幸的是,我一直在瀏覽他們的開發者文檔,我完全不知道我在做什麼。這似乎沒有簡單的功能來獲取系統字體的列表。我必須執行模式搜索,而不是......對嗎?如何使用fontconfig獲取字體列表(C/C++)?

簡而言之,使用fontconfig獲取真實類型字體(它們的族,面和目錄)列表的最佳方式是什麼?當然,如果有比fontconfig更好的東西,我肯定會接受其他解決方案。

回答

4

這不完全是你要求的,但它會給你可用的字體列表。

#include <fontconfig.h> 

FcPattern *pat; 
FcFontSet *fs; 
FcObjectSet *os; 
FcChar8 *s, *file; 
FcConfig *config; 
FcBool result; 
int i; 

result = FcInit(); 
config = FcConfigGetCurrent(); 
FcConfigSetRescanInterval(config, 0); 

// show the fonts (debugging) 
pat = FcPatternCreate(); 
os = FcObjectSetBuild (FC_FAMILY, FC_STYLE, FC_LANG, (char *) 0); 
fs = FcFontList(config, pat, os); 
printf("Total fonts: %d", fs->nfont); 
for (i=0; fs && i < fs->nfont; i++) { 
FcPattern *font = fs->fonts[i];//FcFontSetFont(fs, i); 
FcPatternPrint(font); 
s = FcNameUnparse(font); 
if (FcPatternGetString(font, FC_FILE, 0, &file) == FcResultMatch) { 
    printf("Filename: %s", file); 
} 
printf("Font: %s", s); 
free(s); 
} 
if (fs) FcFontSetDestroy(fs); 
8

我有一個類似的問題,並發現這個職位(fontconfig文檔是有點難以通過)。 MindaugasJ的迴應很有用,但請注意撥打FcPatternPrint()或打印FcNameUnparse()的結果。另外,您需要將FC_FILE參數添加到傳遞給FcObjectSetBuild的參數列表。事情是這樣的:

FcConfig* config = FcInitLoadConfigAndFonts(); 
FcPattern* pat = FcPatternCreate(); 
FcObjectSet* os = FcObjectSetBuild (FC_FAMILY, FC_STYLE, FC_LANG, FC_FILE, (char *) 0); 
FcFontSet* fs = FcFontList(config, pat, os); 
printf("Total matching fonts: %d\n", fs->nfont); 
for (int i=0; fs && i < fs->nfont; ++i) { 
    FcPattern* font = fs->fonts[i]; 
    FcChar8 *file, *style, *family; 
    if (FcPatternGetString(font, FC_FILE, 0, &file) == FcResultMatch && 
     FcPatternGetString(font, FC_FAMILY, 0, &family) == FcResultMatch && 
     FcPatternGetString(font, FC_STYLE, 0, &style) == FcResultMatch) 
    { 
     printf("Filename: %s (family %s, style %s)\n", file, family, style); 
    } 
} 
if (fs) FcFontSetDestroy(fs); 

我有一個稍微不同的問題來解決,我需要找到字體文件傳遞給FreeType的公司給予一定的字體「名」 FC_New_Face()功能。這個代碼能夠使用的fontconfig找到最好的文件,以匹配名稱:

FcConfig* config = FcInitLoadConfigAndFonts(); 

// configure the search pattern, 
// assume "name" is a std::string with the desired font name in it 
FcPattern* pat = FcNameParse((const FcChar8*)(name.c_str())); 
FcConfigSubstitute(config, pat, FcMatchPattern); 
FcDefaultSubstitute(pat); 

// find the font 
FcPattern* font = FcFontMatch(config, pat, NULL); 
if (font) 
{ 
    FcChar8* file = NULL; 
    if (FcPatternGetString(font, FC_FILE, 0, &file) == FcResultMatch) 
    { 
     // save the file to another std::string 
     fontFile = (char*)file; 
    } 
    FcPatternDestroy(font); 
} 

FcPatternDestroy(pat); 
+1

有錯字在你的代碼:FcChar8 *文件,樣式,家庭; 你忘了添加*風格和家庭。段錯誤。 –

+0

如果Mislav的投訴得到解決,我會贊成。 –

+0

謝謝你們的代碼人,但是當我跑這個時,我得到了運行時斷言。輸出:「Microsoft Visual Studio C運行庫已檢測到test-fontconfig.exe中的致命錯誤。」 – codekiddy

相關問題