MFC Support for DirectWrite – Trimming

When using “classic” GDI functions i.e. CDC::DrawText, it’s no sweat to trim with ellipsis a single-line text when that text does not fit in the drawing rectangle width, by specifying DT_WORDBREAK flag. We cannot find a similar flag for CRenderTarget::DrawText or CRenderTarget::DrawTextLayout. However, trimming a text is also possible with DirectDraw. All we have to do is the following:

  1. call IDWriteFactory::CreateEllipsisTrimmingSign to create an inline object for trimming, using ellipsis as the omission sign;
  2. pass the created inline object to IDWriteTextFormat::SetTrimming.

Here is a simple code example in an MFC-based application:

Direct2D text trimming code sample

    // ...
    CD2DTextFormat textFormat(pRenderTarget, m_strFontFamilyName, m_fFontSize);
    IDWriteTextFormat* pTextFormat = textFormat.Get();

    // Set single-line text
    pTextFormat->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);

    // Get IDWriteFactory
    _AFX_D2D_STATE* pD2DState = AfxGetD2DState();
    IDWriteFactory* pDirectWriteFactory = pD2DState->GetWriteFactory();

    // Create an inline object for trimming
    CComPtr<IDWriteInlineObject> spInlineObject;
    pDirectWriteFactory->CreateEllipsisTrimmingSign(textFormat.Get(), &spInlineObject);

    // Call IDWriteTextFormat::SetTrimming to set trimming for text overflowing the layout width.
    // Note: use DWRITE_TRIMMING_GRANULARITY_CHARACTER for trimming at character cluster boundary
    //       or DWRITE_TRIMMING_GRANULARITY_WORD for trimming at word boundary.
    DWRITE_TRIMMING trimming = { DWRITE_TRIMMING_GRANULARITY_CHARACTER, 0, 0 };
    pTextFormat->SetTrimming(&trimming, spInlineObject);
    // ...

    // Draw the text in render target
    pRenderTarget->DrawText(m_strText, rcDraw, m_pTextBrush, &textFormat);

Demo project

Download: MFC Support for DirectWrite Demo (Part 8).zip (1228 downloads)

The demo project contains sample code for all my DirectWrite-related articles. To demonstrate this one, in Trimming granularity combo, select “Character” or “Word”. Also select “No wrap” in Word wrapping combo then have fun.

MFC DirectWrite Demo Project
MFC DirectWrite Demo Project

 

Resources and related articles

Leave a Comment