Colors changing in SDL program I have black and white SDL_Surface and I'm trying to change colors, such as from black to white and from white to red.  I did it, but it is taking too long to work.

SDL_Surface* tempSurface = SDL_DisplayFormat(textSurface);
for(int i=0;i&lt;256;i++){
    SDL_SetColorKey(textSurface,SDL_SRCCOLORKEY,SDL_MapRGB(textSurface-&gt;format,i,i,i));
    SDL_FillRect(tempSurface, 0, SDL_MapRGB(tempSurface-&gt;format, 255, i, i));
    SDL_BlitSurface(textSurface,0,tempSurface,0);
    SDL_FreeSurface(textSurface);
    textSurface=tempSurface;
    tempSurface = SDL_DisplayFormat(textSurface);
}
SDL_FreeSurface(tempSurface);


It works for a few seconds, but it needs to run very fast.  It is C code, but it is not important. SDL is compatible with both languages.

How can I optimize this algorithm? Or can you suggest another way?
It would be helpful to know how textSurface is created. There may be a performance win to be had by using, say, a hardware surface instead of a software surface.

If you are using a surface that supports double buffering I would reccomend using SDL_FLip rather than flipping the buffers yourself using 2 surfaces.

E.g:

SDL_Surface* textSurface;
if(!(textSurface = SDL_SetVideoMode(600, 400, 32, SDL_HWSURFACE)))
    SDL_Quit();

SDL_SetColorKey(textSurface, SDL_SRCCOLORKEY, SDL_MapRGB(textSurface-&gt;format, 255, 0, 255)); //typically we use magenta
for(auto i=0; i&lt;256; i++){
    auto col = SDL_MapRGB(textSurface-&gt;format, i, i, i);
    std::cout &lt;&lt; col &lt;&lt; "," &lt;&lt; SDL_FillRect(textSurface, 0, col) &lt;&lt; std::endl;
    SDL_Flip(textSurface);
}


Note that for your current goal, there is no need to reset the ColorKey each time around the loop.

If you want to run faster than "a few seconds" you certainly won't need to display all 256 intermediate colours to achieve the desired effect. 

SDL_Surface* textSurface;
if(!(textSurface = SDL_SetVideoMode(600, 400, 32, SDL_HWSURFACE)))
    SDL_Quit();

SDL_SetColorKey(textSurface, SDL_SRCCOLORKEY, SDL_MapRGB(textSurface-&gt;format, 255, 0, 255)); //typically we use magenta
auto frame_increment = 4;
for(auto i=0; i&lt;256; i += frame_increment){
    auto col = SDL_MapRGB(textSurface-&gt;format, i, i, i);
    std::cout &lt;&lt; col &lt;&lt; "," &lt;&lt; SDL_FillRect(textSurface, 0, col) &lt;&lt; std::endl;
    SDL_Flip(textSurface);
}


You should determine frame_increment based on your desired time and hardware capabilities.