如何在 Direct2D 中正确初始化 Directwrite IDWriteTextLayout window

How to initialize Directwrite IDWriteTextLayout properly in a Direct2D window

我正在尝试使用 Directwrite 将文本写入 ID2D1HwndRenderTarget* renderTarget-window。这很好用,文本出现在它应该出现的地方。但我觉得我在 Graphics::DrawMyText 做错了什么。我想我也应该在 Graphics::Initialisation 中创建我的 IDWriteTextLayout* textLayout,但如果我这样做,我就不能再更改文本 const wchar_t* wszText。至少,我没有在IDWriteTextLayout接口

中找到任何辅助函数

那么一直创建和释放我的 IDWriteTextLayout 是正确的,还是有办法像其他接口一样只需要创建一次?

#include<dwrite.h>

class Graphics
{
    IDWriteFactory* writeFactory;
    IDWriteTextLayout* textLayout;
    IDWriteTextFormat* textFormat; 
}

Graphics() // constructor
{
    writeFactory = NULL;
    textLayout = NULL;
    textFormat = NULL; 
}

Graphics::~Graphics() // destructor
{
    if (writeFactory) writeFactory->Release();
    if (textLayout) textLayout->Release();
    if (textFormat) textFormat->Release();
}

bool Graphics::Initialise(HWND windowsHandle)
{
    res = writeFactory->CreateTextFormat(
    L"Lucida Console",
    NULL,
    DWRITE_FONT_WEIGHT_REGULAR,
    DWRITE_FONT_STYLE_NORMAL,
    DWRITE_FONT_STRETCH_NORMAL,
    10.0f,
    L"en-us",
    &textFormat
    );
    if (res != S_OK) return false;

    return true;
}

void Graphics::DrawMyText(const wchar_t* wszText, float x, float y, float boxWidth,
                          float boxHeight, float r, float g, float b, float a)
{
    writeFactory->CreateTextLayout(wszText, (UINT32)wcslen(wszText), textFormat,
                                   boxWidth, boxHeight, &textLayout);
    brush->SetColor(D2D1::ColorF(r, g, b, a));
    renderTarget->DrawTextLayout(D2D1::Point2F(x, y), textLayout, brush);
    textLayout->Release(); // don't forget this one to prevent memory leaks
}

DWrite 布局的文本确实是固定的,您的选择是创建(和释放)布局对象或使用 IDWriteTextAnalyzer(以及 IDWriteTextAnalysisSource/IDWriteTextAnalysisSink)的更困难的路线。如果布局的文本是可变的就好了,但 MS 根本没有做出这样的选择。