【问题标题】:ttf Text wont show up in SDLttf 文本不会出现在 SDL 中
【发布时间】:2015-01-01 19:58:24
【问题描述】:

无论我尝试什么,我都无法使用 SDL_ttf 将我的文本加载到 SDL 2.0 中的纹理中。

这是我的 textToTexture 代码

void sdlapp::textToTexture(string text, SDL_Color textColor,SDL_Texture* textTexture)
{
    //free prevoius texture in textTexture if texture exists
    if (textTexture != nullptr || NULL)
    {
        SDL_DestroyTexture(textTexture);
    }
    SDL_Surface* textSurface = TTF_RenderText_Solid(m_font, text.c_str(), textColor);
    textTexture = SDL_CreateTextureFromSurface(m_renderer, textSurface);
    //free surface
    SDL_FreeSurface(textSurface);
}

然后这里是我加载纹理和文本

bool sdlapp::loadMedia()
{
    bool success = true;
    //load media here

    //load font
    m_font = TTF_OpenFont("Fonts/MotorwerkOblique.ttf", 28);

    //load text
    SDL_Color textColor = { 0x255, 0x255, 0x235 };
    textToTexture("im a texture thing", textColor, m_font_texture);

    return success;
}

然后这是我用来渲染它的代码

void sdlapp::render()
{
    //clear the screen
    SDL_RenderClear(m_renderer);
    //do render stuff here
    SDL_Rect rect= { 32, 64, 128, 32 };
    SDL_RenderCopy(m_renderer, m_font_texture, NULL, NULL);
    //update the screen to the current render
    SDL_RenderPresent(m_renderer);
}

有谁知道我做错了什么? 在此先感谢 JustinWeq。

【问题讨论】:

  • 首先要做的是在代码中检查一些错误 - 在加载资产或创建纹理/表面后检查空值
  • 感谢您的建议,在检查空值后,我立即注意到 m_font 和 m_font_texture 都为空。这使我意识到字体加载和从加载的字体中获取纹理。然后我意识到这意味着 TTF 失败了,所以我的第一反应是我没有调用 TTF_Init(),结果证明这是问题所在。

标签: render sdl-2 sdl-ttf


【解决方案1】:

textToTexture 使用 SDL_ttf 呈现文本,然后将生成的 SDL_Texture 地址分配给名为 textTexture 的变量。问题是,textTexture 是一个局部变量,指向与 m_font_texture 相同的地址。它们不是同一个变量,它们是指向同一个地方的不同变量,因此您不会更改任何被调用者变量。

关于指针的说明,我建议查看question 4.8 of the C-FAQ

我会让textToTexture返回新的纹理地址,并且不要费心释放不由它管理的资源(m_font_texture属于sdlapp,它应该由它管理)。

【讨论】:

  • 好的,我接受了您的建议,并让 textToTexture 返回一个指向新纹理(textTexture)的指针,但它仍然无法正常工作。代码中也应该有其他内容,谢谢您的回复。如果可以的话,我会支持你,但不幸的是我的声誉不够高。
  • 好的,我让它工作了,看来我只是忘了调用 TTF_Init()。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2019-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-25
  • 1970-01-01
相关资源
最近更新 更多