### Enumerate System Fonts with DirectWrite Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/introducing-directwrite This C++ example demonstrates how to enumerate all font families installed on the system using the DirectWrite API. It retrieves font family names and prints them to the console. Ensure you have the necessary DirectWrite headers and libraries linked. ```cpp #include #include #include #include // SafeRelease inline function. template inline void SafeRelease(T **ppT) { if (*ppT) { (*ppT)->Release(); *ppT = NULL; } } void wmain() { IDWriteFactory* pDWriteFactory = NULL; HRESULT hr = DWriteCreateFactory( DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), reinterpret_cast(&pDWriteFactory) ); IDWriteFontCollection* pFontCollection = NULL; // Get the system font collection. if (SUCCEEDED(hr)) { hr = pDWriteFactory->GetSystemFontCollection(&pFontCollection); } UINT32 familyCount = 0; // Get the number of font families in the collection. if (SUCCEEDED(hr)) { familyCount = pFontCollection->GetFontFamilyCount(); } for (UINT32 i = 0; i < familyCount; ++i) { IDWriteFontFamily* pFontFamily = NULL; // Get the font family. if (SUCCEEDED(hr)) { hr = pFontCollection->GetFontFamily(i, &pFontFamily); } IDWriteLocalizedStrings* pFamilyNames = NULL; // Get a list of localized strings for the family name. if (SUCCEEDED(hr)) { hr = pFontFamily->GetFamilyNames(&pFamilyNames); } UINT32 index = 0; BOOL exists = false; wchar_t localeName[LOCALE_NAME_MAX_LENGTH]; if (SUCCEEDED(hr)) { // Get the default locale for this user. int defaultLocaleSuccess = GetUserDefaultLocaleName(localeName, LOCALE_NAME_MAX_LENGTH); // If the default locale is returned, find that locale name, otherwise use "en-us". if (defaultLocaleSuccess) { hr = pFamilyNames->FindLocaleName(localeName, &index, &exists); } if (SUCCEEDED(hr) && !exists) // if the above find did not find a match, retry with US English { hr = pFamilyNames->FindLocaleName(L"en-us", &index, &exists); } } // If the specified locale doesn't exist, select the first on the list. if (!exists) index = 0; UINT32 length = 0; // Get the string length. if (SUCCEEDED(hr)) { hr = pFamilyNames->GetStringLength(index, &length); } // Allocate a string big enough to hold the name. wchar_t* name = new (std::nothrow) wchar_t[length+1]; if (name == NULL) { hr = E_OUTOFMEMORY; } // Get the family name. if (SUCCEEDED(hr)) { hr = pFamilyNames->GetString(index, name, length+1); } if (SUCCEEDED(hr)) { // Print out the family name. wprintf(L"%s\n", name); } SafeRelease(&pFontFamily); SafeRelease(&pFamilyNames); delete [] name; } SafeRelease(&pFontCollection); SafeRelease(&pDWriteFactory); } ``` -------------------------------- ### Get Window DPI and Scale Window Size (GDI) Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/how-to-ensure-that-your-application-displays-properly-on-high-dpi-displays Use GetDeviceCaps with LOGPIXELSX and LOGPIXELSY to retrieve DPI values. Scale the desired window dimensions (e.g., 640x480) by the DPI and divide by the default DPI (96). ```C++ FLOAT dpiX, dpiY; HDC screen = GetDC(0); dpiX = static_cast(GetDeviceCaps(screen, LOGPIXELSX)); dpiY = static_cast(GetDeviceCaps(screen, LOGPIXELSY)); ReleaseDC(0, screen); hWnd = CreateWindow( TEXT("DirectWriteApp"), TEXT("DirectWrite Demo App"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, static_cast(dpiX * 640.f / 96.f), static_cast(dpiY * 480.f / 96.f), NULL, NULL, hInstance, NULL); ``` -------------------------------- ### Implement DrawGlyphRun for Custom Renderer Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/render-to-a-gdi-surface Implement the DrawGlyphRun method in a custom text renderer. This example passes the drawing call to the IDWriteBitmapRenderTarget to perform the actual glyph rendering. ```cpp STDMETHODIMP GdiTextRenderer::DrawGlyphRun( __maybenull void* clientDrawingContext, FLOAT baselineOriginX, FLOAT baselineOriginY, DWRITE_MEASURING_MODE measuringMode, __in DWRITE_GLYPH_RUN const* glyphRun, __in DWRITE_GLYPH_RUN_DESCRIPTION const* glyphRunDescription, IUnknown* clientDrawingEffect ) { HRESULT hr = S_OK; // Pass on the drawing call to the render target to do the real work. RECT dirtyRect = {0}; hr = pRenderTarget_->DrawGlyphRun( baselineOriginX, baselineOriginY, measuringMode, glyphRun, pRenderingParams_, RGB(0,200,255), &dirtyRect ); return hr; } ``` -------------------------------- ### IDWriteFontSet4::ConvertWeightStretchStyleToFontAxisValues Example Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/font-selection This function demonstrates how to use IDWriteFontSet4::ConvertWeightStretchStyleToFontAxisValues to convert traditional font parameters (weight, stretch, style) into font axis values, which can then be used with IDWriteFontSet4::GetMatchingFonts. ```APIDOC ## IDWriteFontSet4::ConvertWeightStretchStyleToFontAxisValues ### Description Converts traditional font parameters (weight, stretch, style) into font axis values. This is useful when an application needs to support older font specification methods alongside modern axis-based selection. ### Method C++ Function Call ### Parameters - **factory** (IDWriteFactory7*) - Pointer to the DirectWrite factory. - **familyName** (const WCHAR*) - The family name of the font. - **styleParams** (FontStyleParams) - A structure containing traditional font parameters like weight, stretch, and style. - **axisValues** (std::vector) - A vector to which the converted axis values will be appended. - **allowedSimulations** (DWRITE_FONT_SIMULATIONS) - Flags specifying allowed font simulations. ### Response Appends converted DWRITE_FONT_AXIS_VALUE structures to the provided `axisValues` vector. ### Code Example ```cpp struct FontStyleParams { FontStyleParams() {} FontStyleParams(DWRITE_FONT_WEIGHT fontWeight) : fontWeight{ fontWeight } {} FontStyleParams(float fontSize) : fontSize{ fontSize } {} DWRITE_FONT_WEIGHT fontWeight = DWRITE_FONT_WEIGHT_NORMAL; DWRITE_FONT_STRETCH fontStretch = DWRITE_FONT_STRETCH_NORMAL; DWRITE_FONT_STYLE fontStyle = DWRITE_FONT_STYLE_NORMAL; float fontSize = 0.0f; }; // MatchFont calls IDWriteFontSet4::ConvertWeightStretchStyleToFontAxisValues to convert // the input parameters to axis values and then calls MatchAxisValues. // void MatchFont( IDWriteFactory7* factory, _In_z_ WCHAR const* familyName, FontStyleParams styleParams = {}, std::vector axisValues = {}, DWRITE_FONT_SIMULATIONS allowedSimulations = DWRITE_FONT_SIMULATIONS_BOLD | DWRITE_FONT_SIMULATIONS_OBLIQUE ) { wil::com_ptr fontSet2; THROW_IF_FAILED(factory->GetSystemFontSet(/*includeDownloadableFonts*/ false, &fontSet2)); wil::com_ptr fontSet; THROW_IF_FAILED(fontSet2->QueryInterface(&fontSet)); // Ensure the total number of axis values can't overflow a UINT32. size_t const inputAxisCount = axisValues.size(); if (inputAxisCount > UINT32_MAX - DWRITE_STANDARD_FONT_AXIS_COUNT) { THROW_HR(E_INVALIDARG); } // Reserve space at the end of axisValues vector for the derived axis values. // The maximum number of derived axis values is DWRITE_STANDARD_FONT_AXIS_COUNT. axisValues.resize(inputAxisCount + DWRITE_STANDARD_FONT_AXIS_COUNT); // Call ConvertWeightStretchStyleToFontAxisValues to get derived axis values // and append them to the existing axisValues vector. THROW_IF_FAILED(fontSet->ConvertWeightStretchStyleToFontAxisValues( styleParams.fontWeight, styleParams.fontStretch, styleParams.fontStyle, styleParams.fontSize, axisValues.data() + inputAxisCount // Start writing at the reserved space )); // Call MatchAxisValues with the combined list of axis values. MatchAxisValues(fontSet.get(), familyName, axisValues, allowedSimulations); } ``` ``` -------------------------------- ### Handle Color Font Glyphs with DirectWrite Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/color-fonts Use a switch statement to determine the glyph image format and call the appropriate Direct2D drawing function. This example handles PNG and SVG formats. ```cpp switch (colorRun->glyphImageFormat) { case DWRITE_GLYPH_IMAGE_FORMATS_PNG: // Draw the PNG glyph, for example with // ID2D1DeviceContext4::DrawColorBitmapGlyphRun. break; case DWRITE_GLYPH_IMAGE_FORMATS_SVG: // Draw the SVG glyph, for example with // ID2D1DeviceContext4::DrawSvgGlyphRun. break; // ...etc. } } } return hr; } ``` -------------------------------- ### Create Path Geometry and Get Glyph Run Outline Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/how-to-add-custom-drawing-efffects-to-a-text-layout This snippet demonstrates how to create an ID2D1PathGeometry and retrieve the outline of a glyph run using IDWriteFontFace::GetGlyphRunOutline. It also includes transforming the geometry's origin. ```C++ HRESULT hr = S_OK; // Create the path geometry. ID2D1PathGeometry* pPathGeometry = NULL; hr = pD2DFactory_->CreatePathGeometry( &pPathGeometry ); // Write to the path geometry using the geometry sink. ID2D1GeometrySink* pSink = NULL; if (SUCCEEDED(hr)) { hr = pPathGeometry->Open( &pSink ); } // Get the glyph run outline geometries back from DirectWrite and place them within the // geometry sink. if (SUCCEEDED(hr)) { hr = glyphRun->fontFace->GetGlyphRunOutline( glyphRun->fontEmSize, glyphRun->glyphIndices, glyphRun->glyphAdvances, glyphRun->glyphOffsets, glyphRun->glyphCount, glyphRun->isSideways, glyphRun->bidiLevel%2, pSink ); } // Close the geometry sink if (SUCCEEDED(hr)) { hr = pSink->Close(); } // Initialize a matrix to translate the origin of the glyph run. D2D1::Matrix3x2F const matrix = D2D1::Matrix3x2F( 1.0f, 0.0f, 0.0f, 1.0f, baselineOriginX, baselineOriginY ); // Create the transformed geometry ID2D1TransformedGeometry* pTransformedGeometry = NULL; if (SUCCEEDED(hr)) { hr = pD2DFactory_->CreateTransformedGeometry( pPathGeometry, &matrix, &pTransformedGeometry ); } ``` -------------------------------- ### IDWriteFontSet4::GetMatchingFonts Example Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/font-selection This function demonstrates how to use IDWriteFontSet4::GetMatchingFonts to retrieve a list of fonts that match the specified family name and axis values. It also shows how to iterate through the returned font face references. ```APIDOC ## IDWriteFontSet4::GetMatchingFonts ### Description Retrieves a list of fonts in priority order that match the specified family name and axis values. ### Method C++ Function Call ### Parameters - **fontSet** (IDWriteFontSet4*) - Pointer to the font set. - **familyName** (const WCHAR*) - The family name of the font to match. - **axisValues** (std::vector const&) - A vector of DWRITE_FONT_AXIS_VALUE structures specifying the desired font axes. - **allowedSimulations** (DWRITE_FONT_SIMULATIONS) - Flags specifying allowed font simulations (e.g., bold, oblique). ### Response - **matchingFonts** (IDWriteFontSet4*) - A font set containing the matching fonts. ### Code Example ```cpp // Forward declarations of overloaded output operators used by MatchAxisValues. std::wostream& operator<<(std::wostream& out, DWRITE_FONT_AXIS_VALUE const& axisValue); std::wostream& operator<<(std::wostream& out, IDWriteFontFile* fileReference); std::wostream& operator<<(std::wostream& out, IDWriteFontFaceReference1* faceReference); // MatchAxisValues calls IDWriteFontSet4::GetMatchingFonts with the // specified parameters and outputs the matching fonts. // void MatchAxisValues( IDWriteFontSet4* fontSet, _In_z_ WCHAR const* familyName, std::vector const& axisValues, DWRITE_FONT_SIMULATIONS allowedSimulations ) { // Write the input parameters. std::wcout << L"GetMatchingFonts(\"" << familyName << L"\", {"; for (DWRITE_FONT_AXIS_VALUE const& axisValue : axisValues) { std::wcout << L' ' << axisValue; } std::wcout << L" }, " << allowedSimulations << L"):\n"; // Get the matching fonts for the specified family name and axis values. wil::com_ptr matchingFonts; THROW_IF_FAILED(fontSet->GetMatchingFonts( familyName, axisValues.data(), static_cast(axisValues.size()), allowedSimulations, &matchingFonts )); // Output the matching font face references. UINT32 const fontCount = matchingFonts->GetFontCount(); for (UINT32 fontIndex = 0; fontIndex < fontCount; fontIndex++) { wil::com_ptr faceReference; THROW_IF_FAILED(matchingFonts->GetFontFaceReference(fontIndex, &faceReference)); std::wcout << L" " << faceReference.get() << L'\n'; } std::wcout << std::endl; } ``` ``` -------------------------------- ### Format and Draw "Hello World" with DirectWrite and Direct2D Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/introducing-directwrite This C++ code demonstrates how to initialize the DirectWrite factory, create a text format using Arial font, create a solid color brush, and then draw the "Hello World" string using Direct2D's DrawText function. It includes necessary cleanup for released resources. ```cpp HRESULT DemoApp::DrawHelloWorld( ID2D1HwndRenderTarget* pIRenderTarget ) { HRESULT hr = S_OK; ID2D1SolidColorBrush* pIRedBrush = NULL; IDWriteTextFormat* pITextFormat = NULL; IDWriteFactory* pIDWriteFactory = NULL; if (SUCCEEDED(hr)) { hr = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), reinterpret_cast(&pIDWriteFactory)); } if(SUCCEEDED(hr)) { hr = pIDWriteFactory->CreateTextFormat( L"Arial", NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 10.0f * 96.0f/72.0f, L"en-US", &pITextFormat ); } if(SUCCEEDED(hr)) { hr = pIRenderTarget->CreateSolidColorBrush( D2D1:: ColorF(D2D1::ColorF::Red), &pIRedBrush ); } D2D1_RECT_F layoutRect = D2D1::RectF(0.f, 0.f, 100.f, 100.f); // Actually draw the text at the origin. if(SUCCEEDED(hr)) { pIRenderTarget->DrawText( L"Hello World", wcslen(L"Hello World"), pITextFormat, layoutRect, pIRedBrush ); } // Clean up. SafeRelease(&pIRedBrush); SafeRelease(&pITextFormat); SafeRelease(&pIDWriteFactory); return hr; } ``` -------------------------------- ### Get the Font Family Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/font-enumeration Retrieves a specific IDWriteFontFamily object from the font collection by its index. ```APIDOC ## GetFontFamily ### Description Gets a font family object from the collection by its index. ### Method ```cpp IDWriteFontFamily* pFontFamily = NULL; // Get the font family. if (SUCCEEDED(hr)) { hr = pFontCollection->GetFontFamily(i, &pFontFamily); } ``` ``` -------------------------------- ### Configure Project to Use DPI-Aware Manifest Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/how-to-ensure-that-your-application-displays-properly-on-high-dpi-displays Add the VCManifestTool entry to your project's .vcproj file to link the DeclareDPIAware.manifest file. This step is crucial for the DPI awareness declaration to take effect. ```XML ``` -------------------------------- ### Get the Family Names Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/font-enumeration Retrieves an IDWriteLocalizedStrings object containing localized names for the font family. ```APIDOC ## GetFamilyNames ### Description Gets a list of localized strings for the font family name. ### Method ```cpp IDWriteLocalizedStrings* pFamilyNames = NULL; // Get a list of localized strings for the family name. if (SUCCEEDED(hr)) { hr = pFontFamily->GetFamilyNames(&pFamilyNames); } ``` ``` -------------------------------- ### Initialize Text String Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/getting-started-with-directwrite Initialize the text string and store its length. This prepares the string for rendering. ```cpp wszText_ = L"Hello World using DirectWrite!"; cTextLength_ = (UINT32) wcslen(wszText_); ``` -------------------------------- ### Getting Justification Opportunities Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/justification--kerning--and-spacing Identify potential locations for adding justification characters using IDWriteTextAnalyzer1::GetJustificationOpportunities. ```APIDOC ## GetJustificationOpportunities ### Description Analyzes text to identify opportunities where justification characters can be inserted to achieve full line justification. ### Method `IDWriteTextAnalyzer1::GetJustificationOpportunities` ### Parameters - `text` (string): The text to analyze for justification opportunities. - `textLength` (UINT32): The length of the text. - `script` (DWRITE_SCRIPT_ANALYSIS): The script analysis of the text. - `localeName` (string): The locale name. - `textAnalysis` (IDWriteTextAnalysis): An object providing text analysis results. ### Returns - `justificationOpportunities` (DWRITE_JUSTIFICATION_OPPORTUNITY): A structure detailing where justification can be applied. ``` -------------------------------- ### Declare Application as DPI-Aware (Manifest) Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/how-to-ensure-that-your-application-displays-properly-on-high-dpi-displays Create a manifest file to declare your application as DPI-aware. This ensures proper scaling and behavior on high-DPI displays. ```XML true ``` -------------------------------- ### IDWriteAsyncResult Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/interfaces Represents the result of an asynchronous operation. A client can use the interface to wait for the operation to complete, and to get the result. ```APIDOC ## Interface IDWriteAsyncResult ### Description Represents the result of an asynchronous operation. A client can use the interface to wait for the operation to complete, and to get the result. ### Method Not applicable (Interface definition) ``` -------------------------------- ### Getting Kerning Pair Adjustments Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/justification--kerning--and-spacing Retrieve kerning pair adjustments for glyph indices using IDWriteFontFace1::GetKerningPairAdjustments. ```APIDOC ## GetKerningPairAdjustments ### Description Retrieves the kerning pair adjustments for a given array of glyph indices. ### Method `IDWriteFontFace1::GetKerningPairAdjustments` ### Parameters - `glyphIndices` (array of `UINT32`): An array of glyph indices. - `glyphCount` (UINT32): The number of glyphs in the `glyphIndices` array. ### Returns - `glyphAdvanceAdjustments` (array of `INT32`): An array containing the glyph advance adjustments. Returns zeroes if the font does not support the kern table. ``` -------------------------------- ### Get System Font Collection Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/font-enumeration Retrieves the IDWriteFontCollection containing all system fonts. Requires a DirectWrite Factory object. ```cpp IDWriteFontCollection* pFontCollection = NULL; // Get the system font collection. if (SUCCEEDED(hr)) { hr = pDWriteFactory->GetSystemFontCollection(&pFontCollection); } ``` -------------------------------- ### Include Headers for DirectWrite Application Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/font-selection Include necessary headers for DirectWrite, Windows Implementation Libraries (WIL), and standard C++ libraries. ```cpp #include #include #include #include #include ``` -------------------------------- ### IDWriteFontCollection3 Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/interfaces This interface encapsulates a set of fonts, such as the set of fonts installed on the system, or the set of fonts in a particular directory. ```APIDOC ## Interface IDWriteFontCollection3 ### Description This interface encapsulates a set of fonts, such as the set of fonts installed on the system, or the set of fonts in a particular directory. ### Method Not applicable (Interface definition) ``` -------------------------------- ### Test Font Selection with DirectWrite Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/font-selection Demonstrates various scenarios of font matching using the MatchFont function with different parameters like font name, weight, and axis values. Useful for testing font selection logic. ```cpp void TestFontSelection(IDWriteFactory7* factory) { // Request "Cambria" with bold weight, with and without allowing simulations. // - Matches a typographic/WWS family. // - Result includes all fonts in the family ranked by priority. // - Useful because Cambria Bold might have fewer glyphs than Cambria Regular. // - Simulations may be applied if allowed. MatchFont(factory, L"Cambria", DWRITE_FONT_WEIGHT_BOLD); MatchFont(factory, L"Cambria", DWRITE_FONT_WEIGHT_BOLD, {}, DWRITE_FONT_SIMULATIONS_NONE); // Request "Cambria Bold". // - Matches the full name of one static font. MatchFont(factory, L"Cambria Bold"); // Request "Bahnschrift" with bold weight. // - Matches a typographic/WWS family. // - Returns an arbitrary instance of the variable font. MatchFont(factory, L"Bahnschrift", DWRITE_FONT_WEIGHT_BOLD); // Request "Segoe UI Variable" with two different font sizes. // - Matches a typographic family name only (not a WWS family name). // - Font size maps to "opsz" axis value (Note conversion from DIPs to points.) // - Returns an arbitrary instance of the variable font. MatchFont(factory, L"Segoe UI Variable", 16.0f); MatchFont(factory, L"Segoe UI Variable", 32.0f); // Same as above with an explicit opsz axis value. // The explicit value is used instead of an "opsz" value derived from the font size. MatchFont(factory, L"Segoe UI Variable", 16.0f, { { DWRITE_FONT_AXIS_TAG_OPTICAL_SIZE, 32.0f } }); // Request "Segoe UI Variable Display". // - Matches a WWS family (NOT a typographic family). // - The input "opsz" value is ignored; the optical size of the family is used. MatchFont(factory, L"Segoe UI Variable Display", 16.0f); // Request "Segoe UI Variable Display Bold". // - Matches the full name of a variable font instance. // - All input axes are ignored; the axis values of the matching font are used. MatchFont(factory, L"Segoe UI Variable Display Bold", 16.0f); } ``` -------------------------------- ### IDWriteFontCollection2 Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/interfaces This interface encapsulates a set of fonts, such as the set of fonts installed on the system, or the set of fonts in a particular directory. ```APIDOC ## Interface IDWriteFontCollection2 ### Description This interface encapsulates a set of fonts, such as the set of fonts installed on the system, or the set of fonts in a particular directory. ### Method Not applicable (Interface definition) ``` -------------------------------- ### Render Window Contents with Direct2D Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/getting-started-with-directwrite Implement the window rendering logic by creating device resources, beginning and ending the drawing process, clearing the render target, drawing text, and handling potential device loss. ```C++ hr = CreateDeviceResources(); if (SUCCEEDED(hr)) { pRT_->BeginDraw(); pRT_->SetTransform(D2D1::IdentityMatrix()); pRT_->Clear(D2D1::ColorF(D2D1::ColorF::White)); // Call the DrawText method of this class. hr = DrawText(); if (SUCCEEDED(hr)) { hr = pRT_->EndDraw( ); } } if (FAILED(hr)) { DiscardDeviceResources(); } ``` -------------------------------- ### Command-Line Usage String Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/font-selection Defines the usage string for the command-line parser, outlining available options for font selection. ```cpp char const g_usage[] = "ParseCmdLine \n" "\n" " -test Test sample font selection parameters.\n" " Sets the font family name.\n" " -size Sets the font size in DIPs.\n" " -bold Sets weight to bold (700).\n" " -weight Sets a weight in the range 100-900.\n" " -italic Sets style to DWRITE_FONT_STYLE_ITALIC.\n" " -oblique Sets style to DWRITE_FONT_STYLE_OBLIQUE.\n" " -stretch Sets a stretch in the range 1-9.\n" " -: Sets an axis value (for example, -opsz:24).\n" " -nosim Disallow font simulations.\n" "\n"; ``` -------------------------------- ### Get String Length and String Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/font-enumeration Retrieves the length of a font family name string and then the string itself based on the provided index. ```APIDOC ## GetStringLength and GetString ### Description Gets the length of the font family name string and then retrieves the string content. ### Method ```cpp UINT32 length = 0; // Get the string length. if (SUCCEEDED(hr)) { hr = pFamilyNames->GetStringLength(index, &length); } // Allocate a string big enough to hold the name. wchar_t* name = new (std::nothrow) wchar_t[length+1]; if (name == NULL) { hr = E_OUTOFMEMORY; } // Get the family name. if (SUCCEEDED(hr)) { hr = pFamilyNames->GetString(index, name, length+1); } ``` ``` -------------------------------- ### Create Direct2D Render Target and Brush Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/getting-started-with-directwrite Create an ID2D1HwndRenderTarget and an ID2D1SolidColorBrush within the SimpleText::CreateDeviceResources method. This is typically done when the render target is NULL and needs to be initialized with the window's dimensions. ```C++ RECT rc; GetClientRect(hwnd_, &rc); D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top); if (!pRT_) { // Create a Direct2D render target. hr = pD2DFactory_->CreateHwndRenderTarget( D2D1::RenderTargetProperties(), D2D1::HwndRenderTargetProperties( hwnd_, size ), &pRT_ ); // Create a black brush. if (SUCCEEDED(hr)) { hr = pRT_->CreateSolidColorBrush( D2D1::ColorF(D2D1::ColorF::Black), &pBlackBrush_ ); } } ``` -------------------------------- ### Get the System Font Collection Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/font-enumeration Retrieves the IDWriteFontCollection containing all system fonts using the GetSystemFontCollection method of the DirectWrite Factory. ```APIDOC ## GetSystemFontCollection ### Description Retrieves the IDWriteFontCollection containing all system fonts. ### Method ```cpp IDWriteFontCollection* pFontCollection = NULL; // Get the system font collection. if (SUCCEEDED(hr)) { hr = pDWriteFactory->GetSystemFontCollection(&pFontCollection); } ``` ``` -------------------------------- ### Get Font Family Object Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/font-enumeration Retrieves an IDWriteFontFamily object for a specific font family using its index within the collection. ```cpp IDWriteFontFamily* pFontFamily = NULL; // Get the font family. if (SUCCEEDED(hr)) { hr = pFontCollection->GetFontFamily(i, &pFontFamily); } ``` -------------------------------- ### Initialize Translation Matrix Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/how-to-implement-a-custom-text-renderer Creates a 2D transformation matrix to translate the glyph run to its correct baseline origin. The baseline origin coordinates are provided as parameters. ```cpp // Initialize a matrix to translate the origin of the glyph run. D2D1::Matrix3x2F const matrix = D2D1::Matrix3x2F( 1.0f, 0.0f, 0.0f, 1.0f, baselineOriginX, baselineOriginY ); ``` -------------------------------- ### Accessing System Fonts Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/custom-font-sets-win10 DirectWrite provides methods to access fonts installed on the system or available through the Windows font service. ```APIDOC ## Accessing System Fonts ### Description Apps can access fonts installed locally on the system or those provided by the Windows font service. For fonts included with Windows 10 but not installed, use `IDWriteFactory3::GetSystemFontSet` or `IDWriteFactory3::GetSystemFontCollection` with `includeDownloadableFonts` set to TRUE. ### Methods - `IDWriteFactory3::GetSystemFontSet` - `IDWriteFactory::GetSystemFontCollection` - `IDWriteFactory3::GetSystemFontCollection` ``` -------------------------------- ### InlineImage Constructor Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/how-to-add-inline-objects-to-a-text-layout Initializes the InlineImage object, saving the render target and loading a bitmap from a file. Requires a render target, imaging factory, and a URI to the image file. ```cpp InlineImage::InlineImage( ID2D1RenderTarget *pRenderTarget, IWICImagingFactory *pIWICFactory, PCWSTR uri ) { // Save the render target for later. pRT_ = pRenderTarget; pRT_->AddRef(); // Load the bitmap from a file. LoadBitmapFromFile( pRenderTarget, pIWICFactory, uri, &pBitmap_ ); } ``` -------------------------------- ### SetTextAlignment Method Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/how-to-align-text You can align DirectWrite text by using the SetTextAlignment method of the IDWriteTextFormat interface. This example shows how to center the text. ```APIDOC ## SetTextAlignment Method ### Description This method sets the text alignment for the text format. ### Method ```cpp HRESULT SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER); ``` ### Parameters None ### Request Example ```cpp HRESULT hr = pTextFormat_->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER); if (FAILED(hr)) { // Report the error } ``` ### Response None ``` -------------------------------- ### Create Font File Reference from URL Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/custom-font-sets-win10 Creates an IDWriteFontFile object using the remote font file loader interface, specifying the URL to access the font file. The complete URL can be provided in fontFileUrl, or split into base and relative portions. ```cpp IDWriteFontFile* pFontFile; hr = pRemoteFontFileLoader->CreateFontFileReferenceFromUrl( pDWriteFactory, /* baseUrl */ L"https://github.com/", /* fontFileUrl */ L"winjs/winjs/blob/master/src/fonts/Symbols.ttf?raw=true", &pFontFile ); ``` -------------------------------- ### Get the Font Family Count Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/font-enumeration Obtains the total number of font families available in the font collection using the GetFontFamilyCount method. ```APIDOC ## GetFontFamilyCount ### Description Gets the number of font families in the collection. ### Method ```cpp UINT32 familyCount = 0; // Get the number of font families in the collection. if (SUCCEEDED(hr)) { familyCount = pFontCollection->GetFontFamilyCount(); } ``` ``` -------------------------------- ### Getting Justified Glyphs for Complex Scripts Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/justification--kerning--and-spacing Obtain updated glyphs, including justification characters, for complex scripts using IDWriteTextAnalyzer1::GetJustifiedGlyphs. ```APIDOC ## GetJustifiedGlyphs ### Description Fills in new glyphs, including justification characters, for complex scripts where justification has increased glyph advances. ### Method `IDWriteTextAnalyzer1::GetJustifiedGlyphs` ### Parameters - `fontFile` (IDWriteFontFile): Font file object. - `emSize` (FLOAT): The em size of the glyphs. - `script` (DWRITE_SCRIPT_ANALYSIS): The script analysis of the text. - `textLength` (UINT32): The length of the text. - `clusterMap` (array of `UINT32`): The cluster map. - `glyphIndices` (array of `UINT16`): The original glyph indices. - `glyphAdvances` (array of `INT32`): The original glyph advances. - `glyphOffsets` (array of `INT32`): The original glyph offsets. - `glyphProperties` (array of `DWRITE_glyph_properties`): Properties of the glyphs. - `justifiedGlyphAdvances` (array of `INT32`): The justified glyph advances. - `justifiedGlyphOffsets` (array of `INT32`): The justified glyph offsets. ### Returns - `actualGlyphCount` (UINT32): The actual number of glyphs after justification. - `updatedClusterMap` (array of `UINT32`): The updated cluster map. - `updatedGlyphIndices` (array of `UINT16`): The updated glyph indices with inserted justification glyphs. - `updatedGlyphOffsets` (array of `INT32`): The updated glyph offsets. - `updatedGlyphAdvances` (array of `INT32`): The updated glyph advances. ``` -------------------------------- ### MatchFont Function Implementation Details Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/font-selection This section provides insights into how the `MatchFont` function internally processes font requests, including converting input parameters to axis values and matching them against available fonts. ```APIDOC ## MatchFont Function Implementation Details ### Description This section details the internal workings of the `MatchFont` function, including the conversion of font properties to axis values and the subsequent matching process using `MatchAxisValues`. ### Method C++ Function Implementation Snippets ### Code Examples: - **Converting font properties to axis values**: Demonstrates how weight, stretch, style, and font size are converted into derived axis values. - **Matching axis values**: Shows the call to `MatchAxisValues` with combined explicit and derived axis values. ```cpp // Convert the weight, stretch, style, and font size to derived axis values. UINT32 derivedAxisCount = fontSet->ConvertWeightStretchStyleToFontAxisValues( /*inputAxisValues*/ axisValues.data(), static_cast(inputAxisCount), styleParams.fontWeight, styleParams.fontStretch, styleParams.fontStyle, styleParams.fontSize, /*out*/ axisValues.data() + inputAxisCount ); // Resize the vector based on the actual number of derived axis values returned. axisValues.resize(inputAxisCount + derivedAxisCount); // Pass the combined axis values (explicit and derived) to MatchAxisValues. MatchAxisValues(fontSet.get(), familyName, axisValues, allowedSimulations); ``` ### Output Examples: Provides sample output from `GetMatchingFonts` calls, illustrating the fonts found for specific requests and their properties. ``` -------------------------------- ### Create IDWriteFontFile Reference Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/custom-font-sets-win10 Create an IDWriteFontFile object that references a font file on the local file system. This is a prerequisite for adding the font to a font set builder. ```C++ IDWriteFontFile* pFontFile; if (SUCCEEDED(hr)) { hr = pDWriteFactory->CreateFontFileReference(pFilePath, /* lastWriteTime*/ nullptr, &pFontFile); } ``` -------------------------------- ### Getting Pair Kerning Status on Text Layout Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/justification--kerning--and-spacing Query whether pair kerning is enabled for a specific text range in an IDWriteTextLayout1 object. ```APIDOC ## GetPairKerning ### Description Determines if pair kerning is enabled for a given text position and returns the applicable text range. ### Method `IDWriteTextLayout1::GetPairKerning` ### Parameters - `position` (UINT32): The text position to query. ### Returns - `isEnabled` (bool): `true` if pair kerning is enabled, `false` otherwise. - `range` (DWRITE_TEXT_RANGE): The text range for which the pair kerning setting applies. ``` -------------------------------- ### Get Current Transform from Render Target Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/how-to-implement-a-custom-text-renderer Retrieves the current transformation matrix from the Direct2D render target. This is used when rendering to a Direct2D target. ```cpp //forward the render target's transform pRT_->GetTransform(reinterpret_cast(transform)); ``` -------------------------------- ### Create HTTP Font File Loader Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/custom-font-sets-win10 Creates a system-provided implementation of the remote font file loader interface for handling HTTP interactions. Referrer URL and extra headers can be specified if required by the font service. ```cpp IDWriteRemoteFontFileLoader* pRemoteFontFileLoader; if (SUCCEEDED(hr)) { hr = pDWriteFactory->CreateHttpFontFileLoader( /* referrerURL */ nullptr, /* extraHeaders */ nullptr, &pRemoteFontFileLoader ); } ``` -------------------------------- ### Create IDWriteTextLayout Object Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/how-to-perform-hit-testing-on-a-text-layout Create an IDWriteTextLayout interface object by calling CreateTextLayout. Ensure the text layout dimensions match the client rectangle and DPI scaling. ```C++ // Create a text layout using the text format. if (SUCCEEDED(hr)) { RECT rect; GetClientRect(hwnd_, &rect); float width = rect.right / dpiScaleX_; float height = rect.bottom / dpiScaleY_; hr = pDWriteFactory_->CreateTextLayout( wszText_, // The string to be laid out and formatted. cTextLength_, // The length of the string. pTextFormat_, // The text format to apply to the string (contains font information, etc). width, // The width of the layout box. height, // The height of the layout box. &pTextLayout_ // The IDWriteTextLayout interface pointer. ); } ``` -------------------------------- ### Get Font Family Count Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/font-enumeration Obtains the total number of font families available in the system font collection. This count is used for iteration. ```cpp UINT32 familyCount = 0; // Get the number of font families in the collection. if (SUCCEEDED(hr)) { familyCount = pFontCollection->GetFontFamilyCount(); } ``` -------------------------------- ### Create Path Geometry and Geometry Sink Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/how-to-implement-a-custom-text-renderer Initializes an ID2D1PathGeometry and opens an ID2D1GeometrySink for writing geometry data. Ensure the Direct2D factory is available. ```cpp // Create the path geometry. ID2D1PathGeometry* pPathGeometry = NULL; hr = pD2DFactory_->CreatePathGeometry( &pPathGeometry ); // Write to the path geometry using the geometry sink. ID2D1GeometrySink* pSink = NULL; if (SUCCEEDED(hr)) { hr = pPathGeometry->Open( &pSink ); } ``` -------------------------------- ### Get IDWriteGdiInterop Interface Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/interoperating-with-gdi Obtain an IDWriteGdiInterop object using the IDWriteFactory::GetGdiInterop method. This interface is essential for converting between GDI and DirectWrite font structures. ```C++ // Create a GDI interop interface. if (SUCCEEDED(hr)) { hr = g_pDWriteFactory->GetGdiInterop(&g_pGdiInterop); } ``` -------------------------------- ### Get Font Family Name String Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/font-enumeration Retrieves the actual font family name string after determining its length. Allocates memory for the name and then fetches it. ```cpp UINT32 length = 0; // Get the string length. if (SUCCEEDED(hr)) { hr = pFamilyNames->GetStringLength(index, &length); } // Allocate a string big enough to hold the name. wchar_t* name = new (std::nothrow) wchar_t[length+1]; if (name == NULL) { hr = E_OUTOFMEMORY; } // Get the family name. if (SUCCEEDED(hr)) { hr = pFamilyNames->GetString(index, name, length+1); } ``` -------------------------------- ### Include DWriteCore Header Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/dwritecore-overview Include the dwrite_core.h header file to enable DWriteCore APIs. This header defines a token that directs subsequent includes to make all DirectWrite APIs available. ```cpp // pch.h ... // DWriteCore header file. #include ``` -------------------------------- ### Get Memory DC from IDWriteBitmapRenderTarget Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/rendering-directwrite Obtain the memory device context (DC) from an IDWriteBitmapRenderTarget object to draw glyphs. This is part of rendering ClearType to a GDI surface. ```cpp memoryHdc = g_pBitmapRenderTarget->GetMemoryDC(); ``` -------------------------------- ### CustomTextRenderer Constructor - DirectWrite Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/how-to-implement-a-custom-text-renderer Initializes a custom DirectWrite text renderer. Stores Direct2D factory, render target, and brushes, incrementing their reference counts. ```cpp CustomTextRenderer::CustomTextRenderer( ID2D1Factory* pD2DFactory, ID2D1HwndRenderTarget* pRT, ID2D1SolidColorBrush* pOutlineBrush, ID2D1BitmapBrush* pFillBrush ) : cRefCount_(0), pD2DFactory_(pD2DFactory), pRT_(pRT), pOutlineBrush_(pOutlineBrush), pFillBrush_(pFillBrush) { pD2DFactory_->AddRef(); pRT_->AddRef(); pOutlineBrush_->AddRef(); pFillBrush_->AddRef(); } ``` -------------------------------- ### Create Solid Color Brush from Client Drawing Effect Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/how-to-add-custom-drawing-efffects-to-a-text-layout This snippet shows how to create a Direct2D solid color brush based on a provided client drawing effect. If the effect is not available, it defaults to a black brush. ```C++ // If there is a drawing effect create a color brush using it, otherwise create a black brush. if (clientDrawingEffect != NULL) { // Go from IUnknown to ColorDrawingEffect. ColorDrawingEffect *colorDrawingEffect; clientDrawingEffect->QueryInterface(__uuidof(ColorDrawingEffect), reinterpret_cast(&colorDrawingEffect)); // Get the color from the ColorDrawingEffect object. D2D1_COLOR_F color; colorDrawingEffect->GetColor(&color); // Create the brush using the color specified by our ColorDrawingEffect object. if (SUCCEEDED(hr)) { hr = pRT_->CreateSolidColorBrush( color, &pBrush); } SafeRelease(&colorDrawingEffect); } else { // Create a black brush. if (SUCCEEDED(hr)) { hr = pRT_->CreateSolidColorBrush( D2D1::ColorF( D2D1::ColorF::Black ), &pBrush); } } ``` -------------------------------- ### Get Localized Family Names Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/font-enumeration Fetches an IDWriteLocalizedStrings object containing localized names for the current font family. Multiple language versions may be available. ```cpp IDWriteLocalizedStrings* pFamilyNames = NULL; // Get a list of localized strings for the family name. if (SUCCEEDED(hr)) { hr = pFontFamily->GetFamilyNames(&pFamilyNames); } ``` -------------------------------- ### Create IDWriteTextLayout Object Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/how-to-add-inline-objects-to-a-text-layout Create an IDWriteTextLayout interface object by calling CreateTextLayout. Ensure you have the necessary DWrite factory and text format objects. ```cpp // Create a text layout using the text format. if (SUCCEEDED(hr)) { RECT rect; GetClientRect(hwnd_, &rect); float width = rect.right / dpiScaleX_; float height = rect.bottom / dpiScaleY_; hr = pDWriteFactory_->CreateTextLayout( wszText_, // The string to be laid out and formatted. cTextLength_, // The length of the string. pTextFormat_, // The text format to apply to the string (contains font information, etc). width, // The width of the layout box. height, // The height of the layout box. &pTextLayout_ // The IDWriteTextLayout interface pointer. ); } ``` -------------------------------- ### Get Glyph Run Outline Source: https://learn.microsoft.com/en-us/windows/win32/directwrite/how-to-implement-a-custom-text-renderer Retrieves the outline of a glyph run from DirectWrite and populates the geometry sink. This requires a valid font face and glyph run information. ```cpp // Get the glyph run outline geometries back from DirectWrite and place them within the // geometry sink. if (SUCCEEDED(hr)) { hr = glyphRun->fontFace->GetGlyphRunOutline( glyphRun->fontEmSize, glyphRun->glyphIndices, glyphRun->glyphAdvances, glyphRun->glyphOffsets, glyphRun->glyphCount, glyphRun->isSideways, glyphRun->bidiLevel%2, pSink ); } ```