Using SDL_ttf with OpenGL

前端 未结 2 1112
醉话见心
醉话见心 2020-12-04 17:02

I\'m using OpenGL and SDL to create a window in my program.

How do I use SDL_ttf with an OpenGL window?

For example I want to load a font and render some tex

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 17:35

    Here's how to do it:

    1. Initialize SDL and SDL_ttf, and create a window using SDL_SetVideoMode(). Make sure you pass the SDL_OPENGL flag.
    2. Initialize your OpenGL scene (glViewport(), glMatrixMode() etc.).
    3. Render your text with SDL_ttf using e.g. TTF_RenderUTF8_Blended(). The render functions return an SDL_surface, which you have to convert into an OpenGL texture by passing a pointer to the data (surface->pixels) to OpenGL as well as the format of the data. Like this:

      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);
      
    4. Then you can use the texture in OpenGL using glBindTexture() etc. Make sure to call SDL_GL_SwapBuffers() when you're done with drawing.

提交回复
热议问题