Search code examples
csdlsdl-2

SDL2 does not render properly after window resize


I can't draw on the window after increasing its size. I can still draw on the old part. For instance, I have a 100x100 window, I increase its size with SDL_SetWindowSize to 200x200. I can draw to the old 100x100 zone, but the new zone is not usable unless I use a delay before using it.

Here is an example of the problem using SDL_RenderClear:

int main(void)
{
        SDL_Init(SDL_INIT_VIDEO);

        SDL_Window *win = SDL_CreateWindow("test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 100, 100, SDL_WINDOW_SHOWN);
        SDL_Renderer *rend = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);

        /* Draw red window */
        SDL_SetRenderDrawColor(rend, 255, 0, 0, 255);
        SDL_RenderClear(rend);
        SDL_RenderPresent(rend); // Completely red

        SDL_Delay(3000);

        /* Increase window size and draw it green */
        SDL_SetWindowSize(win, 800, 800);
        SDL_SetRenderDrawColor(rend, 0, 255,0, 255);
        SDL_RenderClear(rend);
        SDL_RenderPresent(rend); // Partially green

        SDL_Delay(3000);

        /* Make window blue */
        SDL_SetRenderDrawColor(rend, 0, 0, 255, 255);
        SDL_RenderClear(rend);
        SDL_RenderPresent(rend); // Completely blue

        SDL_Delay(3000);

        SDL_DestroyRenderer(rend);
        SDL_DestroyWindow(win);
        SDL_Quit();
        return 0;
}

This code is supposed to:

  • Create a 100x100 window and color it red then waits 3s.
  • Increase the window size to 800x800 and color it in green then waits 3s.
  • Color the same window in blue then waits 3s.

The code actually does:

  • Create a 100x100 window and color it red then waits 3s.
  • Increase the window size to 800x800 and color only a 100x100 square in green then waits 3s.
  • Color the same window in blue then waits 3s.

When I add a 100ms delay before SDL_RenderPresent(), it works properly. However, I have the same problem on one of my project, and I have to use a 200ms delay for it to work.

Why do I need a delay before rendering? Is there any way to know how much time to wait before SDL_RenderPresent()?


Solution

  • I found out your problem!

    When you create your window, you need to pass the flag SDL_WINDOW_RESIZABLE. Like this:

        SDL_Window *win = SDL_CreateWindow("test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 100, 100, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE );
    

    Make this change and your window will behave correctly.