Beside the font attributes which can be set in the CD2DTextFormat MFC class constructor, DirectWrite supports more formatting for a block of text, e.g. text alignment, word wrapping, line spacing and so on. However, if taking a look at CD2DTextFormat documentation, we cannot find functions for doing that. Don’t worry, that’s not a problem at all: just call CD2DTextFormat::Get to obtain a pointer to contained IDWriteTextFormat interface, then directly call its methods like SetTextAlignment, SetWordWrapping, SetLineSpacing etc.
Formatting a block of text with DirectDraw in MFC applications
Here is a simple example, completing the one from the previous article:
// We've constructed a CD2DTextFormat object with basic text attributes:
// font family name, size, weight, style and stretch.
// Further, let's apply more text block formatting!
// Get IDWriteTextFormat* and set the text alignment
DWRITE_TEXT_ALIGNMENT textAlignment = _GetSelectedTextAlignment();
HRESULT hr = textFormat.Get()->SetTextAlignment(textAlignment);
// Get IDWriteTextFormat* and set the word wrapping
DWRITE_WORD_WRAPPING wordWrapping = _GetSelectedWordWrapping();
hr = textFormat.Get()->SetWordWrapping(wordWrapping);
// Finally, construct a CD2DTextLayout object and draw the text in the render target.
More details can be found in the attached demo application.
- This example shows only how to set text alignment and word wrapping. Of course, you can use any other format supported by IDWriteTextFormat interface.
- Some of Direct2D & DirectWrite features are supported in Windows 8.1 and later and/or may be missing in Windows SDK prior to v8.1, e.g DWRITE_WORD_WRAPPING_CHARACTER value for DWRITE_WORD_WRAPPING enum, which used as argument for IDWriteTextFormat::SetWordWrapping. See the DirectWrite documentation in MSDN.