使用SDL2和OpenGL渲染文本

4

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

我遵循了相同的代码,文本渲染正常。然而,我的问题是OpenGL渲染和代码中使用的SDL_Renderer之间显然存在“冲突”。当我运行场景时,文字会显示出来,但其他所有东西都在闪烁。以下gif显示了此问题:

enter image description here

有没有办法在仅使用SDL2OpenGL而不使用其他库或任何内容的情况下解决这个问题。


也许这个答案可以帮到你:https://dev59.com/Ym435IYBdhLWcg3wqB4x#5289823 - jpw
@jpw 我正在使用SDL2,因此只能使用SDL_CreateWindow而不能使用SDL_SetVideoMode。 - Kakalokia
1个回答

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_TTF实现True Type字体。

绑定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使用一些默认的东西? - Kakalokia
对于OpenGL-不行。OpenGLES-可以。 - e.proydakov
抱歉,这可能不是一个好问题,但在这种情况下我应该传递什么给glDrawArrays? - Kakalokia
感谢您的回复。然而,这仍然没有显示任何内容。另外,我无法访问SDL_Texture的id变量。 - Kakalokia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接