0

我正在使用 DirectX、C++ 制作游戏,其中的不同部分在类中。目前我正在做一个字体类,但是当我去绘制一个字符串时,它没有显示出来,我不知道为什么。很感谢任何形式的帮助。

字体.h

class d2Font
{
public:
    d2Font(void);
    ~d2Font(void);

    void Create(string name, int size, LPDIRECT3DDEVICE9 device);
    void Draw(string text, int x, int y, int width, int height, DWORD format = DT_LEFT, D3DCOLOR colour = D3DCOLOR_XRGB(255, 255, 255));

private:
    LPD3DXFONT font;
};

字体.cpp

d2Font::d2Font(void)
{
font = NULL;
}

d2Font::~d2Font(void)
{
if(font)
    font->Release();
}

void d2Font::Create(string name, int size, LPDIRECT3DDEVICE9 device)
{
LPD3DXFONT tempFont = NULL;
D3DXFONT_DESC desc = {
    size,
    0,
    0,
    0,
    false,
    DEFAULT_CHARSET,
    OUT_TT_PRECIS,
    CLIP_DEFAULT_PRECIS,
    DEFAULT_PITCH,
    (char)name.c_str()
};
D3DXCreateFontIndirect(device, &desc, &tempFont);

font = tempFont;
}

void d2Font::Draw(string text, int x, int y, int width, int height, DWORD format, D3DCOLOR colour)
{
RECT rect = {x, y, width, height};
//SetRect(&rect, x, y, width, height);

font->DrawText(NULL, text.c_str(), -1, &rect, format, colour);
}

编辑:这是 main.cpp 中的代码

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
gameHinstance = hInstance;

gameMain = new d2Main();
testFont = new d2Font();

if(!gameMain->NewWindow(hInstance, hWnd, "Test Game", 800, 400, nCmdShow, false))
{
    MessageBox(NULL, "Error! Unable to create window!", "D2EX", MB_OK | MB_ICONASTERISK);
    return 0;
}

gameMain->GameRunning = true;

testFont->Create("Arial", 12, gameMain->dx->d3ddev);

gameMain->GameLoop();

return 0;
}

void d2Main::GameUpdate()
{
gameMain->dx->d3ddev->BeginScene();
testFont->Draw("HelloWorld!", 10, 10, 200, 30, DT_LEFT, D3DCOLOR_XRGB(0, 255, 0));
gameMain->dx->d3ddev->EndScene();
}
4

2 回答 2

3

字体描述符中显然有一些错误的字段。一个是重量,正如 Roger Rowland 所提到的。另一个是最后一个,FaceName(字体名称)。您正在尝试将指针转换为 char,这会产生不好的结果。如果您的项目配置为使用 Unicode(Visual Studio 中大多数项目类型的默认设置),则 FaceName 成员将是一个 WCHAR 数组,因此您应该使用 wstring。另一件事是您应该检查 D3DXCreateFontIndirect 的返回值(以及返回 HRESULT 的任何其他 D3D 函数和方法):

HRESULT d2Font::Create(const wstring& name, int size, LPDIRECT3DDEVICE9 device)
{
    D3DXFONT_DESC desc = {
        size,
        0,
        400,
        0,
        false,
        DEFAULT_CHARSET,
        OUT_TT_PRECIS,
        CLIP_DEFAULT_PRECIS,
        DEFAULT_PITCH
    };

    wcscpy_s(desc.FaceName, LF_FACESIZE, name.c_str());

    HRESULT hr = D3DXCreateFontIndirect(device, &desc, &font);
    if (FAILED(hr))
        return hr;

    return S_OK;
}
于 2013-04-09T15:08:07.810 回答
1

看起来您为字体粗细指定了零。尝试这样的事情

D3DXFONT_DESC desc = {
size,
    0,
    0,
    400,
    false,
    DEFAULT_CHARSET,
    OUT_TT_PRECIS,
    CLIP_DEFAULT_PRECIS,
    DEFAULT_PITCH,
    (char)name.c_str()
};
于 2013-04-09T13:39:32.847 回答