使用字体资源编译

Compiling with font resource

我在 windows 8.1,visual studio 2017。

我在我正在处理的 directx 项目中使用了这个 pricedown 字体。

我用 AddFontResourceEx 加载它并用 D3DXCreateFont 为它创建字体。

当我点击 "Local Windows Debugger" 时一切正常,字体呈现。无论是发布还是调试模式。 当我通过任何可执行文件时出现问题,它从不呈现所述字体,无论是发布还是调试。

所以我去读书了,我读了 msdn 上的文章,this one 和其他需要的时候。

我不认为我做错了什么,我的资源视图是这样的:

,IDR_FONT1 看起来像这样:

该文件自动加载到解决方案资源管理器中(我没有添加它,VS 从 Resource.rc 文件中添加),如您所见:

具有这些特性:

我是这样加的:

AddFontResourceEx("pricedown.ttf", FR_PRIVATE, 0);
this->createFont("Pricedown", 60, true, false);

createfont 是我添加字体的函数(精简后,它有数组):

bool    D3D9Render::createFont(char *name, int size, bool bold, bool italic)
{
    D3DXCreateFont(m_pD3dDev, size, 0, (bold) ? FW_BOLD : FW_NORMAL, 0, (italic) ? 1 : 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, ANTIALIASED_QUALITY, DEFAULT_PITCH, name, &m_pFont);
    return true;
}

我正在将其编译为 x64 版本。

正如我所说,当我按下 "Local Windows Debugger"(在包括 x64 版本在内的任何模式下)时,它会工作并呈现字体,但是当我转到 project/x64/Release 时,它不会渲染字体。即使可执行文件大小也足够。

GetLastErrorAddFontResource 上是 2 (ERROR_FILE_NOT_FOUND)

我做错了什么?

(把答案读到最后,否则你会浪费很多时间。)

我明白了。我已阅读 this 博客 post。

Here is an example on how to use AddFontMemResourceEx on a font file embedded in the resource.

HINSTANCE hResInstance = AfxGetResourceHandle( ); //Read the edit

HRSRC res = FindResource(
    hResInstance, 
    MAKEINTRESOURCE(IDR_MYFONT),
    L"BINARY"  //Read The Edit
); 
if (res) 
{
    HGLOBAL mem = LoadResource(hResInstance, res);
    void *data = LockResource(mem);
    size_t len = SizeofResource(hResInstance, res);

    DWORD nFonts;
    m_fonthandle = AddFontMemResourceEx(
        data,       // font resource
        len,       // number of bytes in font resource 
        NULL,          // Reserved. Must be 0.
        &nFonts      // number of fonts installed
        );

    if(m_fonthandle==0)
    {
        MessageBox(L"Font add fails", L"Error");
    }
}

虽然你需要afxwin.h,但来自here

afxwin.h is MFC and MFC is not included in the free version of VC++ (Express Edition)


编辑:

你不需要使用AfxGetResourceHandle(为什么你需要afxwin.h),你可以简单地做:

HINSTANCE hResInstance = (HINSTANCE)GetModuleHandle(NULL);

而在 FindResource 中,第三个参数应该是 RT_FONT,所以你会得到:

HRSRC res = FindResource(hResInstance, MAKEINTRESOURCE(IDR_FONT1), RT_FONT);