Cómo dibujar texto

Para dibujar texto con Direct2D, use el método ID2D1RenderTarget::D rawText para texto que tenga un solo formato. O bien, use el método ID2D1RenderTarget::D rawTextLayout para varios formatos, características avanzadas de OpenType o pruebas de posicionamiento. Estos métodos usan la API de DirectWrite para proporcionar una visualización de texto de alta calidad.

El método DrawText

Para dibujar texto con un solo formato, use el método DrawText . Para usar este método, use primero idWriteFactory para crear una instancia de IDWriteTextFormat .

El código siguiente crea un objeto IDWriteTextFormat y lo almacena en la variable m_pTextFormat .

// Create resources which are not bound
// to any device. Their lifetime effectively extends for the
// duration of the app. These resources include the Direct2D and
// DirectWrite factories,  and a DirectWrite Text Format object
// (used for identifying particular font characteristics).
//
HRESULT DemoApp::CreateDeviceIndependentResources()
{
    static const WCHAR msc_fontName[] = L"Verdana";
    static const FLOAT msc_fontSize = 50;
    HRESULT hr;

    // Create a Direct2D factory.
    hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &m_pD2DFactory);

    if (SUCCEEDED(hr))
    {        
        // Create a DirectWrite factory.
        hr = DWriteCreateFactory(
            DWRITE_FACTORY_TYPE_SHARED,
            __uuidof(m_pDWriteFactory),
            reinterpret_cast<IUnknown **>(&m_pDWriteFactory)
            );
    }
    if (SUCCEEDED(hr))
    {
        // Create a DirectWrite text format object.
        hr = m_pDWriteFactory->CreateTextFormat(
            msc_fontName,
            NULL,
            DWRITE_FONT_WEIGHT_NORMAL,
            DWRITE_FONT_STYLE_NORMAL,
            DWRITE_FONT_STRETCH_NORMAL,
            msc_fontSize,
            L"", //locale
            &m_pTextFormat
            );
    }
    if (SUCCEEDED(hr))
    {
        // Center the text horizontally and vertically.
        m_pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
        
        m_pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
    }

    return hr;
}

Dado que los objetos IDWriteFactory e IDWriteTextFormat son recursos independientes del dispositivo, puede mejorar el rendimiento de una aplicación si los crea una sola vez, en lugar de volver a crearlos cada vez que se representa un fotograma.

Después de crear el objeto de formato de texto, puede usarlo con un destino de representación. El código siguiente dibuja el texto mediante el método DrawText del destino de representación (la variable m_pRenderTarget ).

//  Called whenever the application needs to display the client
//  window. This method writes "Hello, World"
//
//  Note that this function will automatically discard device-specific
//  resources if the Direct3D device disappears during function
//  invocation, and will recreate the resources the next time it's
//  invoked.
//
HRESULT DemoApp::OnRender()
{
    HRESULT hr;

    hr = CreateDeviceResources();

    if (SUCCEEDED(hr))
    {
        static const WCHAR sc_helloWorld[] = L"Hello, World!";

        // Retrieve the size of the render target.
        D2D1_SIZE_F renderTargetSize = m_pRenderTarget->GetSize();

        m_pRenderTarget->BeginDraw();

        m_pRenderTarget->SetTransform(D2D1::Matrix3x2F::Identity());

        m_pRenderTarget->Clear(D2D1::ColorF(D2D1::ColorF::White));

        m_pRenderTarget->DrawText(
            sc_helloWorld,
            ARRAYSIZE(sc_helloWorld) - 1,
            m_pTextFormat,
            D2D1::RectF(0, 0, renderTargetSize.width, renderTargetSize.height),
            m_pBlackBrush
            );

        hr = m_pRenderTarget->EndDraw();

        if (hr == D2DERR_RECREATE_TARGET)
        {
            hr = S_OK;
            DiscardDeviceResources();
        }
    }

    return hr;
}

El método DrawTextLayout

El método DrawTextLayout representa un objeto IDWriteTextLayout . Use este método para aplicar varios formatos a un bloque de texto (por ejemplo, la inserción de una parte del texto), para usar características avanzadas de OpenType o para realizar compatibilidad con pruebas de posicionamiento.

El método DrawTextLayout también proporciona ventajas de rendimiento para dibujar el mismo texto repetidamente. El objeto IDWriteTextLayout mide y establece su texto al crearlo. Si crea un objeto IDWriteTextLayout solo una vez y lo reutiliza cada vez que tiene que volver a dibujar el texto, el rendimiento mejora porque el sistema no tiene que medir y volver a diseñar el texto.

Para poder usar el método DrawTextLayout , debe usar un IDWriteFactory para crear objetos IDWriteTextFormat e IDWriteTextLayout . Una vez creados estos objetos, llame al método DrawTextLayout .

Para obtener más información y ejemplos, vea la información general sobre el formato y el diseño de texto .

Drawtext

DrawTextLayout

IDWriteTextFormat

IDWriteTextLayout

Formato y diseño de texto