使用 Direct2D 進行渲染
Direct2D 提供多種方法,可以將文字使用 IDWriteTextFormat 或 IDWriteTextLayout 格式化後呈現在 Direct2D 表面上。
渲染由IDWriteTextFormat描述的文字
若要使用 IDWriteTextFormat 物件來呈現字串,以描述整個字串的格式,請使用 Direct2D提供的 ID2D1RenderTarget::DrawText 方法。
藉由擷取轉譯區域的維度來定義文字配置的區域,並建立具有相同維度的 Direct2D 矩形。
D2D1_RECT_F layoutRect = D2D1::RectF( static_cast<FLOAT>(rc.left) / dpiScaleX_, static_cast<FLOAT>(rc.top) / dpiScaleY_, static_cast<FLOAT>(rc.right - rc.left) / dpiScaleX_, static_cast<FLOAT>(rc.bottom - rc.top) / dpiScaleY_ );
使用 ID2D1RenderTarget::DrawText 方法和 IDWriteTextFormat 物件將文字轉譯到畫面。 ID2D1RenderTarget::DrawText 方法會使用下列參數:
- 要轉譯的字串。
- IDWriteTextFormat 介面的指標。
- Direct2D 版面配置矩形。
- 介面的指標,這個介面會公開 ID2D1Brush。
pRT_->DrawText( wszText_, // The string to render. cTextLength_, // The string's length. pTextFormat_, // The text format. layoutRect, // The region of the window where the text will be rendered. pBlackBrush_ // The brush used to draw the text. );
呈現 IDWriteText 版面配置物件
若要使用 IDWriteTextLayout 物件所指定的文字版面設定來繪製文字,請將 MultiformattedText::DrawText 方法中的程式碼更改為使用 IDWriteTextLayout::DrawTextLayout。
宣告 D2D1_POINT_2F 變數,並將其設定為視窗的左上角點。
D2D1_POINT_2F origin = D2D1::Point2F( static_cast<FLOAT>(rc.left / dpiScaleX_), static_cast<FLOAT>(rc.top / dpiScaleY_) );
呼叫 ID2D1RenderTarget::DrawTextLayout 方法,通過 Direct2D 渲染目標,並傳遞 IDWriteTextLayout 指標,以將文字繪製到螢幕上。
pRT_->DrawTextLayout( origin, pTextLayout_, pBlackBrush_ );