I want to render some text using a gradient instead of a solid color, but I can't figure out how to. I first load a gradient like this:

SDL_Surface* gradient = IMG_Load("blue-cian.png");

then I render the text I'm using:

SDL_Surface* text = TTF_RenderText_Blended(font, "Text", 30);

then I want to blit the text to the gradient but only keeping the pixels inside the text not the ones surrounding it to create a texture and render it to the screen. I guess I need to use SDL_SetSurfaceAlphaMod and/or SDL_SetSurfaceBlendMode to use only the opaque pixels when blitting the two surfaces. But I don't completely understand how that works and I only get either just a square colored with the gradient:


or a completely transparent square.

This is how it is supposed to look


but I just can't do it, please tell/explain me how to use the rendered text surface as an aplha mask for the gradient.


I've been combing through SDL functions to see if there's anything useful, and I might have found one solution, albeit rather expensive. I'm sure there's a better method out there.

  • Create your gradient and text as SDL_Surfaces.
  • Process every pixel of the texture's Surface to determine if it is transparent or not. If it is transparent, set its color to some arbitrary color you never intend to use. If the pixel is not transparent, set it to be transparent. You should be able to complete this just by using SDL_GetRGBA and SDL_MapRGBA.
  • Blit your font surface onto your gradient surface. This should give you your desired font, but with an opaque background.
  • Again, process every pixel; if the pixel's color is equal to the arbitrary color you set it to earlier, set it to be transparent.

This should hopefully give you exactly what you want, but I have not tried it myself. Check out this post on Stack Overflow to see a similar example.

  • \$\begingroup\$ Thank your for your answer but now I am trying to do it with textures instead of surfaces so I posted this besides I don't know how to access pixels from a surface. \$\endgroup\$ Jul 13 '14 at 1:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.