How I can add a shadow to a texture on SDL2?

Viewed 719

So, I'm making a 2D game and I have some textures. I will like some of them to drop a shadow, there is something like drop-shadow in css for SDL2?

2 Answers

Since noone mentionned it yet, here it is:

int SDL_SetTextureColorMod(SDL_Texture* texture,
                           Uint8        r,
                           Uint8        g,
                           Uint8        b)

https://wiki.libsdl.org/SDL_SetTextureColorMod

This function multiplies a texture color channels when copying it to the SDL_Renderer*. Using it with 0 as r, g and b arguments would make your texture pitch black but not affect the alpha, so the texture would keep its shape (like in the case of a transparent PNG). You just have to copy that shadow before (= behind) your texture, with a slight offset. You can also change the overall transparency of the shadow, with SDL_SetTextureAlphaMod(SDL_Texture* texture, Uint8 a)

Just don't forget to set the values back to 255 when you're done.


Code example:

SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
// [...] draw background, etc... here

SDL_Rect characterRect;
// [...] fill the rect however you want
SDL_Rect shadowRect(characterRect);
shadowRect.x += 30; // offsets the shadow
shadowRect.y += 30;

SDL_SetTextureColorMod(characterTexture, 0, 0, 0);                // makes the texture black
SDL_SetTextureAlphaMod(characterTexture, 191);                    // makes the texture 3/4 of it's original opacity      
SDL_RenderCopy(renderer, characterTexture, NULL, &shadowRect);    // draws the shadow
SDL_SetTextureColorMod(characterTexture, 255, 255, 255);          // sets the values back to normal
SDL_SetTextureAlphaMod(characterTexture, 255);
SDL_RenderCopy(renderer, characterTexture, NULL, &characterRect); // draws the character

// [...] draw UI, additionnal elements, etc... here
SDL_RenderPresent(renderer);
Related