Galaxy
Galaxy

Reputation: 2491

Why is SDL2 window fading out?

I want a quick fix to this issue:

I wrote a simple program to play around with the SDL2 libraries. A cyan box moves along a blue background from left to right. Then the window closes.

The problem is that the window's color "fades out" while the program is running. The contrast decreases significantly and it's annoying. Sometimes it happens when the box is in the middle of the window. Sometimes it happens when the box reaches the right side of the window. Sometimes it doesn't happen at all. This fading of colors seems to be sporadic and random. It is a run time issue. Theoretically, I do not see any issue with the code. What is wrong?

#include "SDL.h"
#include <stdio.h>

#ifdef __cplusplus
  extern "C"
#endif
int main(int argc, char* argv[])
{
    SDL_Init(SDL_INIT_VIDEO);

    SDL_Window*   window = NULL;
    SDL_Renderer* renderer = NULL;

    window = SDL_CreateWindow("Boxes", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, 0);
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    SDL_Rect myBox = { 200, 150, 50, 50  };

    int go = 0;
    while (go <= 590) {
      myBox.x = go;

      SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255);

      SDL_RenderClear(renderer);

      SDL_SetRenderDrawColor(renderer, 0, 255, 255, 255);

      SDL_RenderFillRect(renderer, &myBox);

      SDL_RenderPresent(renderer);

      if (go == 0)
        SDL_Delay(2000);

      SDL_Delay(100);

      go += 10;
    }

    SDL_Delay(2000);

    SDL_DestroyWindow(window);
    SDL_DestroyRenderer(renderer);

    SDL_Quit();

    return EXIT_SUCCESS;
}

This is how it's supposed to look like.

The color fades out!

Upvotes: 0

Views: 410

Answers (1)

HolyBlackCat
HolyBlackCat

Reputation: 96906

That's a classical SDL mistake.

You're not handling events that your window receives, and because of that your OS assumes that your program has hung up.

Inside of your while loop, add following:

SDL_Event e;
while (SDL_PollEvent(&e))
    if (e.type == SDL_QUIT)
        return 0;

Upvotes: 3

Related Questions