简体   繁体   English

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

[英]How to initialize Directwrite IDWriteTextLayout properly in a Direct2D window

I'm trying to write text to my ID2D1HwndRenderTarget* renderTarget -window using Directwrite.我正在尝试使用 Directwrite 将文本写入我的ID2D1HwndRenderTarget* renderTarget -window。 That works good and text appears where it should.这很好用,文本出现在它应该出现的地方。 But i have the feeling i'm doing something wrong in Graphics::DrawMyText .但我觉得我在Graphics::DrawMyText做错了什么。 I think I should create my IDWriteTextLayout* textLayout also in the Graphics::Initialisation but if I do that, i cannot alter the text const wchar_t* wszText anymore.我想我也应该在Graphics::Initialisation中创建我的IDWriteTextLayout* textLayout ,但如果我这样做,我将无法再更改文本const wchar_t* wszText At least, I did not find any helper function in IDWriteTextLayout interface至少,我在IDWriteTextLayout界面中没有找到任何帮助程序function

So is it correct to create and release my IDWriteTextLayout all the time, or is there a way I only have to create it once like the other interfaces?那么始终创建和释放我的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
}

The text of a DWrite layout is indeed fixed, your choices are either to create (and release) layout objects or go the much harder route of using IDWriteTextAnalyzer (along with IDWriteTextAnalysisSource/IDWriteTextAnalysisSink). DWrite 布局的文本确实是固定的,您的选择是创建(和释放)布局对象或 go 使用 IDWriteTextAnalyzer(连同 IDWriteTextAnalysisSource/IDWriteTextAnalysisSink)更难的途径。 It would have been nice if the text of a layout were mutable but MS simply didn't make that choice.如果布局的文本是可变的,那就太好了,但 MS 根本没有做出那个选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM