让SDL_ttf与SDL2玩得很好

Getting SDL_ttf to play nice with SDL2

本文关键字:很好 SDL2 SDL ttf      更新时间:2023-10-16

我最近开始从使用SDL(1.2.15)迁移到SDL2(2.0.0),并且以前依赖于使用扩展库SDL_ttf(2.0.11)来渲染字体。当我尝试使用与SDL2版本一SDL相同的文本库(诚然,尚未正式发布)时,它编译得很好。然而,当我运行可执行文件时(我目前正在使用VS2012作为Desktop),我会得到以下错误:

Unhandled exception at 0x6C7D8C24 (SDL2.dll) in test.exe: 0xC0000005: Access violation reading location 0x00000045.

据我所知,这是由于以下代码。我创建了一个Window类来封装一些常见的SDL函数:

window.cpp:

SDL_Texture* Window::RenderText(const std::string &message, const std::string &fontFile, SDL_Color color, int fontSize){
//Open the font
TTF_Font *font = nullptr;
font = TTF_OpenFont(fontFile.c_str(), fontSize);
if (font == nullptr)
    throw std::runtime_error("Failed to load font: " + fontFile + TTF_GetError());
//Render the message to an SDL_Surface, as that's what TTF_RenderText_X returns
SDL_Surface *surf = TTF_RenderText_Blended(font, message.c_str(), color);
SDL_Texture *texture = SDL_CreateTextureFromSurface(mRenderer.get(), surf);
//Clean up unneeded stuff
SDL_FreeSurface(surf);
TTF_CloseFont(font);
return texture;
}

它被绊倒了

SDL_Texture *texture = SDL_CreateTextureFromSurface(mRenderer.get(), surf);

线,其中创建的SDL_Surface与SDL2的Surfaces定义不兼容,因此当它试图将SDL_Surfaces转换为SDL_Texture时,它会翻转出来。

我不认为我是唯一一个遇到这个问题的人,所以有没有SDL_ttf的变通方法/更新版本可以解决这个问题,或者我应该推迟到SDL2,直到我可以让字体正常工作?

您检查了SDL_TTF的Mercurial存储库吗?它似乎已经针对SDL2进行了更新,同步最新的代码并构建它肯定是值得的。