Text in OpenGL using SDL_TTF

我们两清 提交于 2020-01-17 05:58:19

问题


I'm a beginner in OpenGL and I've created a function to write text in OpenGL using SDL_TTF. Here is the code for my function:

#define WINDOW_WIDTH 832
#define WINDOW_HEIGHT 487
#define glVertex2px(x,y) glVertex2d((double)(x) * 2.0 / (double)WINDOW_WIDTH - 1.0, 1.0 - (double)(y) * 2.0 / (double)WINDOW_HEIGHT);
void glWriteText2d(TTF_Font *font,const char *text,SDL_Color color,const int x,const int y){
    GLuint texture;
    SDL_Surface *surface;
    surface = TTF_RenderText_Blended(font,text,color);
    glGenTextures(1,&texture);
    glBindTexture(GL_TEXTURE_2D,texture);
    gluBuild2DMipmaps(GL_TEXTURE_2D,4,surface->w,surface->h,GL_RGBA,GL_UNSIGNED_BYTE,surface->pixels);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
    GLboolean textureIsEnabled = glIsEnabled(GL_TEXTURE_2D);
    glEnable(GL_TEXTURE_2D);
    glColor3ub(255,255,255);
    glBegin(GL_QUADS);
        glTexCoord2f(0,0);
        glVertex2px(x,y);
        glTexCoord2f(0,1);
        glVertex2px(x,y + surface->h);
        glTexCoord2f(1,1);
        glVertex2px(x + surface->w,y + surface->h);
        glTexCoord2f(1,0);
        glVertex2px(x + surface->w,y);
    glEnd();
    if(!textureIsEnabled){
        glDisable(GL_TEXTURE_2D);
    }
}

This function doesn't work because when I use it, it draws a rectangle which is the color of color at the place where the text should be. What should I change in my code so that it works?


回答1:


Your resulting texture is filled with solid colour. What makes it shape the text is alpha channel, but you have no alpha blending enabled so you don't see it. Add

glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

or at least alpha test (will produce sharper edges due to lack of blending - for some fonts it even look better that way).

Also note that you didn't freed neither generated SDL_Surface nor GL texture; that way you'll quickly run out of memory. Texture could be reused and SDL_Surface may be freed as soon as you copied data to GL texture.



来源:https://stackoverflow.com/questions/38750624/text-in-opengl-using-sdl-ttf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!