We can change the color of a text range by passing a brush object to IDWriteTextLayout::SetDrawingEffect. Here is a simple example.
An example of using IDWriteTextLayout::SetDrawingEffect
LRESULT CDirectWriteDemoView::OnDraw2D(WPARAM wParam, LPARAM lParam) { CHwndRenderTarget* pRenderTarget = (CHwndRenderTarget*)lParam; // Please, see the demo application for more details. // ... // init color effects _InitColorEffects(pRenderTarget, spTextLayout); // Draw the text in the render target. pRenderTarget->DrawTextLayout(CD2DPointF(), // upper-left corner of the text spTextLayout.get(), // text layout object &CD2DSolidColorBrush // default brush used for text (pRenderTarget, D2D1::ColorF(D2D1::ColorF::Black))); return 0; }
void CDirectWriteDemoView::_InitColorEffects(CHwndRenderTarget* pRenderTarget, std::shared_ptr<CD2DTextLayout> spTextLayout) { CDirectWriteDemoDoc* pDoc = _GetDocument(); DWRITE_TEXT_RANGE textRange; if(pDoc->FindTextRange(_T("BLUE"), textRange)) _SetTextLayoutDrawingEffect(pRenderTarget, spTextLayout, D2D1::ColorF(D2D1::ColorF::Blue), textRange); if(pDoc->FindTextRange(_T("YELLOW"), textRange)) _SetTextLayoutDrawingEffect(pRenderTarget, spTextLayout, D2D1::ColorF(D2D1::ColorF::Yellow), textRange); if(pDoc->FindTextRange(_T("RED"), textRange)) _SetTextLayoutDrawingEffect(pRenderTarget, spTextLayout, D2D1::ColorF(D2D1::ColorF::Red), textRange); }
void CDirectWriteDemoView::_SetTextLayoutDrawingEffect(CHwndRenderTarget* pRenderTarget, std::shared_ptr<CD2DTextLayout> spTextLpayout, D2D1_COLOR_F color, DWRITE_TEXT_RANGE textRange) { CD2DSolidColorBrush* pBrush = new CD2DSolidColorBrush(pRenderTarget, color); pBrush->Create(pRenderTarget); spTextLayout->Get()->SetDrawingEffect(static_cast<IUnknown*>(pBrush->Get()), textRange); }
So far, there’s no much “special effects” in the above example. Although a little bit more difficult, it is possible to make more customized rendering like text highlighting, double/triple underline/strikethrough and so on. This will be the subject of a future article.
Demo application
Download: MFC Support for DirectWrite Demo - Part 6.zip (51)
Resources and related articles
- MSDN: IDWriteTextLayout::SetDrawingEffect method
- Codexpert blog: Direc2D and DirectWrite topics