这几天在写字体安装器,所以研究了下freetype、fontconfig这两个库。

装上Dev开发包

1
sudo apt install libglib2.0-dev libfontconfig1-dev libfreetype6-dev

在你的Qt项目pro文件添加

1
2
CONFIG += c++11 link_pkgconfig
PKGCONFIG += freetype2 fontconfig glib-2.0

头文件

1
2
3
4
5
6
7
8
#include <glib.h>
#include <fontconfig/fontconfig.h>
#include <ft2build.h>

#include FT_FREETYPE_H
#include FT_TYPE1_TABLES_H
#include FT_SFNT_NAMES_H
#include FT_TRUETYPE_IDS_H

代码之路

版本一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
QStringList Utils::getAllFontName()
{
QStringList families;
FT_Library library = 0;
FT_Face face = 0;
FcConfig *config = FcConfigGetCurrent();
FcStrList *strList = FcConfigGetFontDirs(config);
FcChar8 *path;

FT_Init_FreeType(&library);

while ((path = FcStrListNext(strList)) != NULL) {
const QString pathStr = QString::fromLatin1((char *)path);
const QDir dir(pathStr);
const QFileInfoList infoList = dir.entryInfoList(QDir::Files);

for (const QFileInfo &info : infoList) {
const QString filePath = info.absoluteFilePath();

// filter other font files.
if (isFontSuffix(info.suffix())) {
FT_New_Face(library, info.absoluteFilePath().toLatin1().data(), 0, &face);
families << face->family_name;
}
}
}

// destroy object.
FT_Done_Face(face);
FT_Done_FreeType(library);
FcStrListDone(strList);

return families;
}

版本二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
QStringList Utils::getAllFontName()
{
QStringList families;
FcPattern *pattern = FcNameParse((FcChar8 *) ":");
FcObjectSet *objectset = FcObjectSetBuild(FC_FILE, NULL);
FcFontSet *fontset = FcFontList(NULL, pattern, objectset);
FcInit();

for (int i = 0; i < fontset->nfont; ++i) {
FcChar8 *family;
if (FcPatternGetString(fontset->fonts[i], FC_FILE, 0, &family) == FcResultMatch) {
qDebug() << (char *)family;
}
}

// destroy object.
if (objectset)
FcObjectSetDestroy(objectset);
if (pattern)
FcPatternDestroy(pattern);
if (fontset)
FcFontSetDestroy(fontset);

return families;
}

另附char *转换QString:

1
2
3
4
5
6
char *s = "hello world";
QString str = nullptr;
for (int i = 0; i < sizeof(s); ++i) {
char ch = static_cast<char>(s[i]);
str.push_back(ch);
}