使用ttf库SDL C进行分段错误

时间:2017-04-20 10:22:42

标签: c sdl true-type-fonts

我正在尝试使用C将文本放在带有sdl的窗口上。 我跟着这个 tutorial. 如果我按照一步一步的步骤,在他初始化表面之后:

 SDL_Color color = { 255, 255, 255 };
 SDL_Surface * surface = TTF_RenderText_Solid(font,"Welcome to Programmer's Ranch", color);

我得到分段错误。 所以在这一点上我的代码就是这样:

#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>


int main(int argc, char ** argv)
{
    int quit = 0;
    SDL_Event event;

    SDL_Init(SDL_INIT_VIDEO);

    TTF_Init(); //Initialise ttf library

    SDL_Window * window = SDL_CreateWindow("SDL_ttf in SDL2", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);
    SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0);

    TTF_Font * font = TTF_OpenFont("arial.ttf", 25);//Load text(to put after renderere initialisation!)The first is the path to the TrueType Font (TTF) that it needs to load. The second is the font size (in points, not pixels). In this case we're loading Arial with a size of 25.
    SDL_Color color = { 255, 255, 255 };
    SDL_Surface * surface = TTF_RenderText_Solid(font, "Welcome to Programmer's Ranch", color);

    while (!quit)
    {
        SDL_WaitEvent(&event);

        switch (event.type)
        {
            case SDL_QUIT:
            quit = 1;
            break;
        }
    }

    TTF_CloseFont(font);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    TTF_Quit();
    SDL_Quit();

    return 0;
}

虽然他的整个源代码可用here,但它无论如何都不起作用。

1 个答案:

答案 0 :(得分:0)

arial.ttf的路径很可能是错误的。确保从根项目目录中包含该文件的完整路径。

每次启动或加载 / 中的内容时,您应该做的就是添加异常处理程序。例如:

#include <stdexcept>

try
{
    TTF_Font * font = TTF_OpenFont("arial.ttf", 25);
    if (font == NULL)
    {
        throw(::std::runtime_error("Font failed to load! ERROR: "));
    }
}
catch (std::runtime_error const& msg)
{
    printf("%s", msg.what());
    if (SDL_GetError() != NULL)
    {
        printf("%s", SDL_GetError());
    }
    if (TTF_GetError() != NULL)
    {
        printf("%s", TTF_GetError());
    }
}