How can I keep my texture center during resizing the window

I wrote a snippet. Its main logic just like this:

int main() {
    // create a window and a texture and other initializations

    // always render the texture to the center of the window
    bool quit = false;
    while (!quit) {
        while (SDL_PollEvent(&e)) {
            if (e.type == SDL_QUIT) {
                quit = true;
            }
            if (e.type == SDL_WINDOWEVENT) {
                switch (e.window.event) {
                    // when window is resized, repaint the texture to the center
                    case SDL_WINDOWEVENT_SIZE_CHANGED: {
                        windowWidth = e.window.data1;
                        windowHeight = e.window.data2;
                        RenderMyTextureToCenter(windowWidth, windowHeight);
                    }
                }
            }
        }
    }
}

It partly meeted my requirement.I found that texture only repainted when resizing was totally done.But if I keep dragging my mouse and zoom the window, the texture will not repaint.I want my texture always keep in the center even during the resizing.How can I realize that?

are you on Windows?

  1. write an event filter function following this signature: SDL2/SDL_EventFilter - SDL2 Wiki
    • you must return 1 from this event filter. if you return zero, you break SDL.
    • for SDL_WINDOWEVENT_SIZE_CHANGED and SDL_WINDOWEVENT_RESIZED, execute code strictly related to resizing, NOT rendering
    • catch SDL_WINDOWEVENT_EXPOSED, then execute render-related code
    • these three events are guaranteed to be watched/filtered in main thread, despite documentation saying they can be called from any thread. you can write assertions to ensure this, if you feel paranoid
  2. during initialization, activate the callback with an event watcher: SDL2/SDL_AddEventWatch - SDL2 Wiki

see this: Is it thread-safe to render inside event watcher?
and this: Live-resize of an SDL window

1 Like

There is an easier solution. Just register an event watcher callback using the SDL_AddEventWatch() function, detect the SDL_EVENT_WINDOW_RESIZED or SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED event in it, update your window data there and repaint the entire window. It is safe to repaint the window in the watcher. The new window size is delivered in the event, but you can also get it using the SDL_GetWindowSize() function.

This works perfectly fine, and even smoother performance can be achieved by disabling VSync while the window is repainted (and turning it back on after repainting).

1 Like