SDL_ttf"无法加载字体文件"使用c ++中的SDL2

时间:2016-04-02 03:33:27

标签: c++ sdl-2 sdl-ttf

我有以下代码在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函数。

3 个答案:

答案 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” 希望这会有所帮助!