Font Management

DirectWrite provides a comprehensive set of interfaces for locating, enumerating, and managing fonts. This article outlines the primary concepts, key interfaces, and best practices for working with font collections and font families.

Key Concepts

System Font Collection

The most common scenario is to use the system font collection. Example code:

// Initialize DirectWrite factory
Microsoft::WRL::ComPtr<IDWriteFactory> factory;
DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), &factory);

// Retrieve the system font collection
Microsoft::WRL::ComPtr<IDWriteFontCollection> systemFonts;
factory->GetSystemFontCollection(&systemFonts, FALSE);

// Enumerate font families
UINT32 familyCount = systemFonts->GetFontFamilyCount();
for (UINT32 i = 0; i < familyCount; ++i) {
    Microsoft::WRL::ComPtr<IDWriteFontFamily> family;
    systemFonts->GetFontFamily(i, &family);
    // Get family name
    Microsoft::WRL::ComPtr<IDWriteLocalizedStrings> names;
    family->GetFamilyNames(&names);
    // ... retrieve and display the name ...
}

Creating a Custom Font Collection

Custom collections enable loading fonts from memory, network, or other sources. The steps are:

  1. Implement IDWriteFontFileLoader to load font data.
  2. Implement IDWriteFontFileEnumerator to enumerate loaded files.
  3. Register the loader with IDWriteFactory::RegisterFontFileLoader.
  4. Create the collection using IDWriteFactory::CreateCustomFontCollection.
Tip: Use Microsoft::WRL::ComPtr for automatic reference counting and avoid memory leaks.

Common Methods

InterfaceMethodDescription
IDWriteFactoryGetSystemFontCollectionRetrieves the system font collection.
IDWriteFactoryCreateCustomFontCollectionCreates a custom font collection using a loader.
IDWriteFontFamilyGetFamilyNamesGets localized family names.
IDWriteFontFamilyGetFirstMatchingFontRetrieves a font face matching requested weight/style/stretch.
IDWriteFontCreateFontFaceCreates an IDWriteFontFace for the font.

Related Topics