Skip to content

Instantly share code, notes, and snippets.

@cfillion cfillion/fctest.cpp
Last active Aug 16, 2018

What would you like to do?
Font family matching with FontConfig demo
// c++ -lfontconfig fctest.cpp
// ./a.out 'DejaVu Sans Mono' monospace 'Andale Mono' 'Ubuntu Mono' Lato
#include <cstdio>
#include <fontconfig/fontconfig.h>
class FontConfig {
FontConfig() : m_config(FcInitLoadConfigAndFonts()) {}
FontConfig(const FontConfig &) = delete;
~FontConfig() { FcConfigDestroy(m_config); }
operator FcConfig *() { return m_config; }
FcConfig *m_config;
class FontPattern {
FontPattern(FcPattern *p = FcPatternCreate()) : m_pattern(p) {}
FontPattern(const FontPattern &) = delete;
~FontPattern() { FcPatternDestroy(m_pattern); }
operator bool() const { return m_pattern; }
template<typename T> T get(const char *object, int n = 0) const;
template<typename T> bool add(const char *object, T val);
FontPattern bestMatch(FcConfig * = nullptr);
FcPattern *m_pattern;
const char *FontPattern::get(const char *object, const int n) const {
FcChar8 *value;
if(FcPatternGetString(m_pattern, object, n, &value) == FcResultMatch)
return reinterpret_cast<const char *>(value);
return nullptr;
bool FontPattern::add(const char *object, const char *val) {
return FcPatternAddString(m_pattern, object, reinterpret_cast<const FcChar8 *>(val));
bool FontPattern::add(const char *object, const int val) {
return FcPatternAddInteger(m_pattern, object, val);
FontPattern FontPattern::bestMatch(FcConfig *cfg) {
FcConfigSubstitute(cfg, m_pattern, FcMatchPattern);
FcResult result;
return {FcFontMatch(cfg, m_pattern, &result)};
int main(const int argc, const char *argv[]) {
FontConfig fc;
for(int i = 1; i < argc; ++i) {
FontPattern query;
query.add(FC_FAMILY, argv[i]);
// query.add(FC_WEIGHT, FC_WEIGHT_BOLD);
// query.add(FC_SLANT, FC_SLANT_ITALIC);
// ...
const FontPattern &font = query.bestMatch(fc);
if(font) {
printf("found font matching '%s': '%s' in '%s'\n", argv[i],
font.get<const char *>(FC_FAMILY), font.get<const char *>(FC_FILE));
printf("no font matching '%s' found\n", argv[i]);
return 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.