将SDL_ttf与OpenGL一起使用

Khe*_*esh 18 opengl sdl sdl-ttf

我正在使用OpenGL和SDL在我的程序中创建一个窗口.

如何在OpenGL窗口中使用SDL_ttf?

例如,我想加载一个字体并渲染一些文字.我想使用SDL OpenGL表面绘制文本.

Ant*_*tti 34

这是怎么做的:

  1. 初始化SDL和SDL_ttf,并使用创建窗口SDL_SetVideoMode().确保你通过SDL_OPENGL旗帜.
  2. 初始化OpenGL场景(glViewport(),glMatrixMode()等等).
  3. 使用例如,使用SDL_ttf渲染文本TTF_RenderUTF8_Blended().渲染函数返回一个SDL_surface,您必须通过将指针传递给data(surface->pixels)到OpenGL以及数据格式来转换为OpenGL纹理.像这样:

    colors = surface->format->BytesPerPixel;
    if (colors == 4) {   // alpha
        if (surface->format->Rmask == 0x000000ff)
            texture_format = GL_RGBA;
        else
            texture_format = GL_BGRA;
    } else {             // no alpha
        if (surface->format->Rmask == 0x000000ff)
            texture_format = GL_RGB;
        else
            texture_format = GL_BGR;
    }
    
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture); 
    glTexImage2D(GL_TEXTURE_2D, 0, colors, surface->w, surface->h, 0,
                        texture_format, GL_UNSIGNED_BYTE, surface->pixels);
    
    Run Code Online (Sandbox Code Playgroud)
  4. 然后你可以使用OpenGL中的纹理glBindTexture()等.确保SDL_GL_SwapBuffers()在完成绘图时调用.