我有以下代码在SDL2应用程序中绘制一些文本。当我构建并运行时,我始终看到TTF_OpenFont() Failed: Couldn't load font file
的错误。我尝试过以下方法:
SDL_RWFromFile
分别打开文件:http://www.gamedev.net/topic/275525-sdl_ttf-weirdness/ 这是我的代码:
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函数。
答案 0 :(得分:1)
我遇到了这个问题,这是因为链接到错误版本的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。
答案 1 :(得分:0)
My thoughts probably belong in a comment but I don't have enough reputation. You can make sure you're in the right directory by explicitly setting the current working directory (chdir
in unistd.h on Linux, or SetCurrentDirectory
in windows.h on Windows). I don't think you need to include ./
in the file name.
I recall having problems with SDL_ttf when calling TTF_Init
, TTF_Quit
, and then TTF_Init
again. This may not be causing your problem but I would recommend doing your TTF_Init
just once at the beginning of the program and TTF_Quit
once at the end, not every time your constructor runs.
If this doesn't work look into building a debug version of SDL_ttf that will play nicer with GDB.
答案 2 :(得分:0)
我遇到了同样的问题,并设法通过输入字体的完整路径来解决它。
不只是传递字符串“ ./font.ttf”
我用过:“ / User / MyUsername / Projects / MyProject / font.tff” 希望这会有所帮助!