Direct2D Text Concepts

Direct2D provides a rich set of features for rendering text. This section covers the core concepts and components involved in displaying text using Direct2D.

Text Rendering Overview

Direct2D's text rendering capabilities are built upon the Windows text subsystem, leveraging GDI and DirectWrite for high-quality, hardware-accelerated text. You can draw text, format it with various properties, and control its appearance with precision.

Key Components

IDWriteTextFormat

The IDWriteTextFormat interface represents the formatting of a block of text. It defines properties such as:

You create an IDWriteTextFormat object using an IDWriteFactory.

// Example of creating a text format
IDWriteFactory* pDWriteFactory = ...; // Get your IDWriteFactory instance
IDWriteTextFormat* pTextFormat = nullptr;
HRESULT hr = pDWriteFactory->CreateTextFormat(
    L"Segoe UI", // Font family name
    nullptr,     // Font collection (nullptr for system default)
    DWRITE_FONT_WEIGHT_NORMAL,
    DWRITE_FONT_STYLE_NORMAL,
    DWRITE_FONT_STRETCH_NORMAL,
    16.0f,       // Font size in DIPs
    L"en-US",    // Locale name
    &pTextFormat
);
                

IDWriteTextLayout

The IDWriteTextLayout interface represents a block of text that has been analyzed and can be rendered. It builds upon IDWriteTextFormat and allows for more dynamic text manipulation, including:

You create an IDWriteTextLayout object from an IDWriteTextFormat and the text string.

// Example of creating a text layout
IDWriteFactory* pDWriteFactory = ...;
IDWriteTextFormat* pTextFormat = ...;
const WCHAR* text = L"Hello, Direct2D Text!";
IDWriteTextLayout* pTextLayout = nullptr;

HRESULT hr = pDWriteFactory->CreateTextLayout(
    text,
    wcslen(text),
    pTextFormat,
    600.0f, // Max width
    300.0f, // Max height
    &pTextLayout
);
                

Rendering Text

Once you have an IDWriteTextLayout, you can render it to a Direct2D render target using the DrawTextLayout method.

// Example of drawing text
ID2D1DeviceContext* pDeviceContext = ...; // Get your render target
IDWriteTextLayout* pTextLayout = ...;
D2D1_COLOR_F textColor = D2D1::ColorF(D2D1::ColorF::Black);

pDeviceContext->DrawTextLayout(
    D2D1::Point2F(10.0f, 10.0f), // Position
    pTextLayout,
    pDeviceContext->CreateSolidColorBrush(textColor) // Brush for text color
);
                

Text Properties and Formatting

Direct2D and DirectWrite offer extensive control over text appearance:

Important Note on Units

Font sizes in IDWriteTextFormat are specified in device-independent pixels (DIPs). This ensures text scales appropriately across different display resolutions.

Further Reading