【问题标题】:Rendering text with SDL2 and OpenGL使用 SDL2 和 OpenGL 渲染文本
【发布时间】:2015-05-06 23:34:34
【问题描述】:

我一直在尝试使用 SDL2 在我的 OpenGL 场景中进行文本渲染。我碰到的教程就是这个Rendering text

我遵循相同的代码,并且我得到了很好的文本渲染。但是我遇到的问题是 OpenGL 渲染和代码中使用的 SDL_Renderer 之间显然存在“冲突”。当我运行我的场景时,文本显示,但其他一切都在闪烁。以下 gif 显示了该问题:

关于如何克服这个问题的任何想法,同时仍然只使用 SDL2 和 OpenGL,而不是其他库或任何东西。

【问题讨论】:

标签: opengl sdl sdl-2


【解决方案1】:

尝试在纹理中渲染 SDL 文本,例如:

SDL_Texture* renderText(const std::string &message, const std::string &fontFile,
    SDL_Color color, int fontSize, SDL_Renderer *renderer)
{
    //Open the font
    TTF_Font *font = TTF_OpenFont(fontFile.c_str(), fontSize);
    if (font == nullptr){
        logSDLError(std::cout, "TTF_OpenFont");
        return nullptr;
    }   
    //We need to first render to a surface as that's what TTF_RenderText
    //returns, then load that surface into a texture
    SDL_Surface *surf = TTF_RenderText_Blended(font, message.c_str(), color);
    if (surf == nullptr){
        TTF_CloseFont(font);
        logSDLError(std::cout, "TTF_RenderText");
        return nullptr;
    }
    SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surf);
    if (texture == nullptr){
        logSDLError(std::cout, "CreateTexture");
    }
    //Clean up the surface and font
    SDL_FreeSurface(surf);
    TTF_CloseFont(font);
    return texture;
}

见http://www.willusher.io/sdl2%20tutorials/2013/12/18/lesson-6-true-type-fonts-with-sdl_ttf/

绑定 SDL_Texture

void SDL_BindTexture(SDL_Texture *t)
{
  glBindTexture(GL_TEXTURE_2D, t->id);
}

并使用 glDrawArrays() 进行绘制,例如:

const GLfloat quadVertices[] = { -1.0f, 1.0f, 0.0f, 
    1.0f, 1.0f, 0.0f, 
    1.0f,-1.0f, 0.0f,
    -1.0f,-1.0f, 0.0f
}; 

glVertexPointer(3, GL_FLOAT, 0, quadVertices);
glDrawArrays(GL_QUADS, 0, 4);

【讨论】:

  • 在这种情况下我需要着色器吗?或者是 OpenGL 使用了一些默认的东西。
  • 对于 OpenGL - 没有。 OpenGLES - 是的。
  • 抱歉,这可能不是一个好问题,但在这种情况下,我应该将什么传递给 glDrawArrays?
  • 感谢您的回复。但是,这仍然没有显示任何内容。我也无法访问 SDL_Texture 的 id 变量。
猜你喜欢
  • 1970-01-01
  • 2021-05-14
  • 1970-01-01
  • 2016-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-11
相关资源
最近更新 更多