我有以下代码来在 SDL2 应用程序中绘制一些文本。当我构建并运行时,我始终看到 TTF_OpenFont() Failed: Couldn't load font file
错误。我尝试过以下方法:
- 确保字体文件位于正在运行的程序的当前目录中。事实上,我已将字体放在几乎可以运行程序的任何目录中,并尝试使用绝对路径。
- 设置不同的权限并拥有文件
- 使用
SDL_RWFromFile
单独打开文件,如下所述:http://www.gamedev.net/topic/275525-sdl_ttf-weirdness/ - 下载并重新编译了较新版本的 SDL_ttf (2.0.14)
这是我的代码:
void SDLRenderer::drawText(
const Vector2d& pos,
string message,
const Color& color)
{
if(!TTF_WasInit()) {
cerr << "TTF_Init failed " << TTF_GetError() << endl;
exit(1);
}
TTF_Font* fixed = TTF_OpenFont("./DejaVuSansMono.ttf", 16);
if (fixed == NULL) {
cerr << "TTF_OpenFont() Failed: " << TTF_GetError() << endl;
TTF_Quit();
SDL_Quit();
exit(1);
}
...
我还从此代码类的构造函数中调用 TTF_Init()
。我也有点不确定如何进一步调试,因为 gdb 在错误发生后甚至没有给出回溯,并且似乎不允许我进入 TTF_OpenFont 函数。
最佳答案
我遇到了这个问题,它是由链接到错误版本的 SDL_ttf 库引起的。我使用的是 SDL 2.0,但我链接的是 libSDL_ttf.so
而不是 libSDL2_ttf.so
。 libSDL_ttf.so
适用于 SDL 1.2,与 SDK 2.0 不兼容。
我原来的命令行是:
$ gcc -o showfont showfont.c `sdl2-config --cflags --libs` -lSDL_ttf
$ ./showfont /usr/share/fonts/truetype/freefont/FreeSans.ttf
Couldn't load 18 pt font from /usr/share/fonts/truetype/freefont/FreeSans.ttf: Couldn't load font file
我通过链接 libSDL2_ttf.so
修复了它:
$ gcc -o showfont showfont.c `sdl2-config --cflags --libs` -lSDL2_ttf
$ ./showfont /usr/share/fonts/truetype/freefont/FreeSans.ttf
Font is generally 21 big, and string is 21 big
showfont.c
程序是 example included with SDL_ttf .
关于c++ - SDL_ttf "Couldn' t 用 C++ 中的 SDL2 加载字体文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36368862/