简体   繁体   English

如何在 SDL2 上为纹理添加阴影?

[英]How I can add a shadow to a texture on SDL2?

So, I'm making a 2D game and I have some textures.所以,我正在制作一个 2D 游戏,我有一些纹理。 I will like some of them to drop a shadow, there is something like drop-shadow in css for SDL2?我希望他们中的一些人投下阴影,SDL2 的 css 中有类似阴影的东西吗?

Render the texture first, then render a slightly larger semi-transparent gray square slightly behind it.先渲染纹理,然后在其后面渲染一个稍大的半透明灰色方块。 If you want rounded corners, use a shader that increases alpha as you get further from the corners .如果您想要圆角,请使用随着离角越远而增加 alpha 的着色器

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 https://wiki.libsdl.org/SDL_SetTextureColorMod

This function multiplies a texture color channels when copying it to the SDL_Renderer*.此 function 在将其复制到 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).将其与 0 一起使用为 r、g 和 b arguments 将使您的纹理变黑但不会影响 alpha,因此纹理将保持其形状(就像在透明 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)您还可以更改阴影的整体透明度,使用SDL_SetTextureAlphaMod(SDL_Texture* texture, Uint8 a)

Just don't forget to set the values back to 255 when you're done.完成后不要忘记将值设置回 255。


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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM