【发布时间】:2026-01-16 05:50:02
【问题描述】:
我正在尝试使用 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
}
【问题讨论】:
-
renderTarget是从哪里来的? -
如果您更改文本,您将不得不重新创建布局,但您可以保留格式,这就是您所做的。您还可以缓存布局,直到 CreateTextLayout 的参数发生更改。 docs.microsoft.com/en-us/windows/win32/directwrite/…
-
@MariusBancila 渲染目标已在其他地方初始化和定义,但这与这个问题无关,但我列出了它的名称和类型。
-
CreateTextLayout接收一个文本字符串并生成一个表示完全分析和格式化结果的对象。如果您想更改文本字符串内容,您可以使用新的文本字符串再次调用CreateTextLayout。 -
@RitaHan-MSFT 感谢您的建议。这就是我在显示的代码中所做的,但我希望我可以创建一次
IDWriteTextLayout并像其他ID-elements 一样重用它。
标签: c++ winapi directwrite