IDWriteFactory::CreateTextLayout方法导致窗口突然关闭



在我使用Windows API构建的应用程序中,我目前正在将文本写入屏幕。我正在尝试使用CreateTextLayout方法,但使用该特定函数时,我遇到了无法解决的问题。当我刚运行我的应用程序时,我启动得很好,然后它就退出了,没有任何错误警告。使用断点,我将问题追溯到该函数。这是我用来称呼它的代码:

IDWriteFactory* writeFactory;
IDWriteTextFormat* writeTextFormat;
IDWriteTextLayout* writeTextLayout;
HRESULT App::CreateDeviceIndependentResources()
{
HRESULT hr;
// Create a Direct2D factory.
hr = D2D1CreateFactory(
D2D1_FACTORY_TYPE_SINGLE_THREADED,
&writeFactory
);

if (SUCCEEDED(hr))
{
hr = DWriteCreateFactory(
DWRITE_FACTORY_TYPE_SHARED,
__uuidof(writeFactory),
reinterpret_cast<IUnknown**>(&writeFactory)
);
}
if (writeFactory == NULL)
OutputDebugStringA("NULLn");
if (SUCCEEDED(hr))
{
hr =  writeFactory->CreateTextFormat(
L"Times New Roman",
NULL,
DWRITE_FONT_WEIGHT_NORMAL,
DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
14.0f,
L"EN-US",
&writeTextFormat
);
}
if (SUCCEEDED(hr))
{
// Create a DirectWrite text format object.
hr = writeFactory->CreateTextLayout(
L"Projects",      // The string to be laid out and formatted.
8,  // The length of the string.
writeTextFormat,  // The text format to apply to the string (contains font information, etc).
10.0f,         // The width of the layout box.
10.0f,        // The height of the layout box.
&writeTextLayout  // The IDWriteTextLayout interface pointer.
);
}
}

我觉得这是非常基本的,因为我刚刚在Microsoft.com上学习了教程;然而,显然有些地方出了问题。我猜测它可能与writeTextFormat有关。它是一个IDWriteTextFormat对象。此外,所有这些对象都在CreateDeviceIndependentResources()函数中初始化。我应该在其他地方初始化它们吗?

您混淆了D2D1CreateFactoryDWriteCreateFactory的使用。

D2D1CreateFactory用于创建ID2D1Factory接口,该接口用于创建用于呈现文本的ID2D1HwndRenderTargetID2D1SolidColorBrush

DWriteCreateFactory用于创建IDWriteFactory接口,该接口是所有DirectWrite对象的根工厂接口。并且使用DirectWrite对象来格式化文本。

例如:

ID2D1HwndRenderTarget* pRT_;
...
pRT_->DrawText(
wszText_,        // The string to render.
cTextLength_,    // The string's length.
pTextFormat_,    // The text format.
layoutRect,       // The region of the window where the text will be rendered.
pBlackBrush_     // The brush used to draw the text.
);

也许您可以从第2部分开始:创建与设备无关的资源。

部分代码:

IDWriteFactory* pDWriteFactory_;
hr = DWriteCreateFactory(
DWRITE_FACTORY_TYPE_SHARED,
__uuidof(IDWriteFactory),
reinterpret_cast<IUnknown**>(&pDWriteFactory_)
);
...
if (SUCCEEDED(hr))
{
// Create a DirectWrite text format object.
hr = pDWriteFactory_->CreateTextLayout(
L"Projects",      // The string to be laid out and formatted.
8,  // The length of the string.
writeTextFormat,  // The text format to apply to the string (contains font information, etc).
10.0f,         // The width of the layout box.
10.0f,        // The height of the layout box.
&writeTextLayout  // The IDWriteTextLayout interface pointer.
);
}

官方示例:HelloWorld

最新更新