Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

sdl - Using SDL_ttf with OpenGL

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 text. I want to draw the text using an SDL OpenGL surface.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...