Reputation: 2137
I can load an image in (png) no problem using SDL_image and also display it perfectly. What I would like to do though is gradually fade the image in from fully transparent to fully opaque. I have seen some tutorials mentioning SDL_SetAlpha
but this is for use on a an SDL_Surface
where as SDL_image loads as SDL_Texture
for the hardware acceleration.
Can anyone help out with how this might be done while maintaining good performance?
Upvotes: 3
Views: 7250
Reputation: 2137
So here is what I found out. To render a texture with alpha you simply need to make a call to SetTextureAlphaMod
passing in a pointer to the texture and an integer in the range 0 - 255.
The function itself is documented here
NB. Alpha modulation is not always supported by the renderer, and the function will return -1 if this is the case (returns 0 for successful call). There is information in the function documentation as to how to detect if your renderer supports alpha modulation.
The next part of my problem was how to perform smooth fading from SDL_TRANSPARENT (0) to SDL_OPAQUE (255). I did this in my variable update function (game is using fixed and variable updates)
#define FADE_SPEED 0.07f;
void SomeClass::UpdateVariable(float elapsedTime)
{
// Check there is a texture
if (texture) {
// Set the alpha of the texture
SDL_SetTextureAlphaMod(texture, alpha);
}
// Update the alpha value
if (alpha < SDL_ALPHA_OPAQUE) {
alphaCalc += FADE_SPEED * elapsedTime;
alpha = alphaCalc;
}
// if alpha is above 255 clamp it
if (alpha >= SDL_ALPHA_OPAQUE) {
alpha = SDL_ALPHA_OPAQUE;
alphaCalc = (float)SDL_ALPHA_OPAQUE;
}
}
Note the use of two alpha variables. alpha
is the actual value which is passed to the function for controlling the texture alpha and is a Uint8. alphaCalc
is a float and is used to store the gradually increasing value from 0 to 255. Every call of the update function sees this value update by a scaler value FADE_SPEED
multiplied by the frame time elapsed. It is then be assigned to the actual alpha value. This is done to maintain a smooth fade as integer rounding prevents a smooth fade using the alpha value alone.
Upvotes: 8