gpt4 book ai didi

c - 使用 ttf 库 SDL C 的段错误

转载 作者:行者123 更新时间:2023-11-30 19:34:42 25 4
gpt4 key购买 nike

我正在尝试使用 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 ,但无论如何它都不起作用。

最佳答案

很可能 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());
}
}

关于c - 使用 ttf 库 SDL C 的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43516799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com