Using SDL_ttf and OpenGL, TTF_RenderUTF8_Blended print Red rectangle

后端 未结 1 473
粉色の甜心
粉色の甜心 2021-01-13 16:05

When I render my text using TTF_RenderUTF8_Blended I obtain a solid rectangle on the screen. The color depends on the one I choose, in my case the rectangle is

1条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-13 16:32

    You've made a fairly common mistake. It's on the OpenGL end of things.

    When you render the textured quad in DrawText(), you enable OpenGL's blending capability, but you never specify the blending function (i.e. how it should be blended)!

    You need this code to enable regular alpha-blending in OpenGL:

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

    This info used to be on the OpenGL website, but I can't find it now.

    That should stop it from coming out solid red. The reasons the others worked is because they're not alpha-blended, they're actually just red-on-black images with no alpha, so the blending function doesn't matter. But the blended one only contains red color, with an alpha channel to make it less-red.

    I notice a few other small problems in your program though.

    In the DrawText() function, you are blitting the surface using SDL and rendering with OpenGL. You should not use regular SDL blitting when using OpenGL; it doesn't work. So this line should not be there:

    SDL_BlitSurface(g_pText, &sourceRect, g_pSurfaceDisplay, NULL);
    

    Also, this line leaks memory:

    g_pText = SDL_DisplayFormatAlpha( TTF_RenderUTF8_Blended(...) );
    

    TTF_RenderUTF8_Blended() returns a pointer to SDL_Surface, which must be freed with SDL_FreeSurface(). Since you're passing it into SDL_DisplayFormatAlpha(), you lose track of it, and it never gets freed (hence the memory leak).

    The good news is that you don't need SDL_DisplayFormatAlpha here because TTF_RenderUTF8_Blended returns a 32-bit surface with an alpha-channel anyway! So you can rewrite this line as:

    g_pText = TTF_RenderUTF8_Blended(g_pFont, "My first Text!", g_textColor);
    

    0 讨论(0)
提交回复
热议问题