使用SDL_ttf用OpenGL

问题描述 投票:19回答:2

我使用OpenGL和SDL建立在我的程序的窗口。

如何使用SDL_ttf与OpenGL窗口?

例如,我要加载的字体和渲染一些文字。我想提请使用OpenGL的SDL表面的文字。

opengl sdl sdl-ttf
2个回答
35
投票

以下是如何做到这一点:

  1. 初始化SDL和SDL_ttf,并使用SDL_SetVideoMode()创建一个窗口。请确保您通过SDL_OPENGL标志。
  2. 初始化OpenGL场景(glViewport()glMatrixMode()等)。
  3. 使用例如SDL_ttf渲染文本TTF_RenderUTF8_Blended()。渲染函数返回SDL_surface,你必须通过传递的指针数据(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);
  4. 然后,你可以使用glBindTexture()等确保调用SDL_GL_SwapBuffers()当你与绘图完成使用纹理在OpenGL。

2
投票

基于断:http://content.gpwiki.org/index.php/SDL_ttf:Tutorials:Fonts_in_OpenGL

下面的代码是如何可以呈现你可能已经建立完成3D模型上文本的例子。

#include "SDL.h"
#include "SDL_ttf.h"

/.../

void RenderText(std::string message, SDL_Color color, int x, int y, int size) {
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glLoadIdentity();

  gluOrtho2D(0, m_Width, 0, m_Height); // m_Width and m_Height is the resolution of window
  glMatrixMode(GL_PROJECTION);
  glPushMatrix();
  glLoadIdentity();

  glDisable(GL_DEPTH_TEST);
  glEnable(GL_TEXTURE_2D);
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  GLuint texture;
  glGenTextures(1, &texture);
  glBindTexture(GL_TEXTURE_2D, texture);

  TTF_Font * font = TTF_OpenFont("pathToFont.ttf", size);
  SDL_Surface * sFont = TTF_RenderText_Blended(font, message, color);

  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, sFont->w, sFont->h, 0, GL_BGRA, GL_UNSIGNED_BYTE, sFont->pixels);

  glBegin(GL_QUADS);
  {
    glTexCoord2f(0,0); glVertex2f(x, y);
    glTexCoord2f(1,0); glVertex2f(x + sFont->w, y);
    glTexCoord2f(1,1); glVertex2f(x + sFont->w, y + sFont->h);
    glTexCoord2f(0,1); glVertex2f(x, y + sFont->h);
  }
  glEnd();

  glDisable(GL_BLEND);
  glDisable(GL_TEXTURE_2D);
  glEnable(GL_DEPTH_TEST);

  glMatrixMode(GL_PROJECTION);
  glPopMatrix();
  glMatrixMode(GL_PROJECTION);
  glPopMatrix();

  glDeleteTextures(1, &texture);
  TTF_CloseFont(font);
  SDL_FreeSurface(sFont);
}

/.../

int main() {

/.../ Render 3D stuff here

  // Prints out "Hello World" at location (5,10) at font size 12!
  SDL_Color color = {255, 0, 0, 0}; // Red
  RenderText("Hello World", color, 5, 10, 12); 

/.../

  return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.