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
- Font collection: A group of font families. The system font collection is accessed via
IDWriteFactory::GetSystemFontCollection. - Font family: Represents a group of typefaces that share a common design. Accessed through
IDWriteFontFamily. - Font face: A specific typeface (e.g., Regular, Bold). Represented by
IDWriteFontFace. - Custom collections: Applications can create custom font collections by implementing
IDWriteFontCollectionLoaderandIDWriteFontFileEnumerator.
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:
- Implement
IDWriteFontFileLoaderto load font data. - Implement
IDWriteFontFileEnumeratorto enumerate loaded files. - Register the loader with
IDWriteFactory::RegisterFontFileLoader. - Create the collection using
IDWriteFactory::CreateCustomFontCollection.
Tip: Use
Microsoft::WRL::ComPtr for automatic reference counting and avoid memory leaks.
Common Methods
| Interface | Method | Description |
|---|---|---|
| IDWriteFactory | GetSystemFontCollection | Retrieves the system font collection. |
| IDWriteFactory | CreateCustomFontCollection | Creates a custom font collection using a loader. |
| IDWriteFontFamily | GetFamilyNames | Gets localized family names. |
| IDWriteFontFamily | GetFirstMatchingFont | Retrieves a font face matching requested weight/style/stretch. |
| IDWriteFont | CreateFontFace | Creates an IDWriteFontFace for the font. |