Search code examples
cfontssdlsdl-2alphablending

Cannot set blend mode on texture obtained from a font with SDL 2 lib in C


I am able to set the blend mode on textures generally using the SDL 2 function:

SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);

However, this doesn't work on textures derived from fonts:

SDL_Surface * fontSurface;
SDL_Texture * fontTexture;
fontSurface = TTF_RenderText_Blended(displayFont, text, color);
//SDL_SetSurfaceBlendMode(fontSurface, SDL_BLENDMODE_BLEND);
fontTexture = SDL_CreateTextureFromSurface(renderer, fontSurface);
int bmr = SDL_SetTextureBlendMode(fontTexture, SDL_BLENDMODE_BLEND);
printf("bmr %d\n", bmr);
SDL_BlendMode bm;
printf("bm %d\n", SDL_GetTextureBlendMode(fontTexture, &bm));

It makes no difference whether or not the font surface has its blend mode set before the texture. The printouts show that the blend setting function returns 0 for success, but the blend mode is 0 for SDL_BLENDMODE_NONE, not 1 for SDL_BLENDMODE_BLEND. Creating the texture with TTF_RenderText_Shaded (with the additional background color parameter) or indeed TTF_RenderText_Solid is not successful either. Is it at all possible to set the blend mode on textures derived from fonts?


Solution

  • Further investigation leads to an answer. It appears from the example code in the SDL_ttf documentation, that only a 3-member SDL_Color value is expected, missing the Alpha of a 4-member struct. With Alpha ignored, the blend mode is not set. Another function allows the Alpha to be used for blending nevertheless:

    int bmr = SDL_SetTextureAlphaMod(fontTexture, color.a);
    

    Problem solved, and I hope this helps others facing the same issue.