Search code examples
c++directxdirect2d

Direct2D CreateTextLayout() - How to get caret coordinates


I am rendering Text using Direct2D starting with a text Layout

HRESULT hr = m_spWriteFactory->CreateTextLayout(
        m_wsText.c_str( ),
        m_wsText.length( ),
        m_spWriteTextFormat.Get( ),
        m_rect.right - m_rect.left - m_spacing.right - m_spacing.left,
        m_rect.bottom - m_rect.top - m_spacing.top - m_spacing.bottom,
        &m_spTextLayout
        );

and then rendering it to a bitmap which I later use with Direct3D

m_sp2DDeviceContext->DrawTextLayout(
                D2D1::Point2F( m_spacing.left, m_spacing.top ),
                m_spTextLayout.Get( ),
                m_spTextBrush.Get( )
                );

I would like to draw a simple thin flashing line as a caret. I know how to draw a line and how to make it appear / disappear.

Question: How do I get the starting point and the end point coordinates for my caret line?

Simplification: If it is much easier to assume that the text consists of one line only, then that's ok. But of course a more general solution is appreciated.


Solution

  • You can get the layout's bounding rectangle via IDWriteTextLayout::GetMetrics.

        DWRITE_TEXT_METRICS textMetrics;
        textLayout->GetMetrics(&textMetrics);
    

    Your rectangle is

        D2D1::RectF( textMetrics.left,
                     textMetrics.top, 
                     textMetrics.left + textMetrics.width,
                     textMetrics.top + textMetrics.height );
    

    You can then draw the caret along the right boundary line.