I'm trying to create an SDL2 application that allows for resizing of windows. However, the surface is not resized when the window is.
I wrote the minimal case to demonstrate my issue.
#include <SDL2/SDL.h>
#include <iostream>
int main(int argc, char **argv) {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window *mainWindow = SDL_CreateWindow(
"Debugging This", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 700,
400, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
SDL_Surface *mainWindowSurface = SDL_GetWindowSurface(mainWindow);
int quit = 0;
SDL_Event e;
while (!quit) {
while (SDL_PollEvent(&e)) {
switch (e.type) {
case SDL_QUIT:
quit = 1;
break;
case SDL_WINDOWEVENT:
if (e.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
std::cout << "Window dimensions (w/h): " << e.window.data1 << "/"
<< e.window.data2 << "\n";
std::cout << "surface dimensions (w/h): " << mainWindowSurface->w
<< "/" << mainWindowSurface->h << "\n";
}
break;
}
}
SDL_FillRect(mainWindowSurface, NULL,
SDL_MapRGB(mainWindowSurface->format, 0xFF, 0xFF, 0xFF));
SDL_UpdateWindowSurface(mainWindow);
}
SDL_FreeSurface(mainWindowSurface);
mainWindowSurface = NULL;
SDL_DestroyWindow(mainWindow);
mainWindow = NULL;
SDL_Quit();
return 0;
}
As you can see, while you resize the window, it prints the window dimensions to the console, along with the surface dimensions (of the window surface). As you alter the window's size, the outputted window dimensions change as expected - but the surface dimensions remain static. How can I set this up in such a way that the window surface adjusts itself to fill out the window as intended during resizing?
I cannot use renderers and textures because I need to alter the surface often, which makes it more beneficial to use surfaces than textures.
You need to call SDL_GetWindowSurface()
again after the window is resized to get the current surface.
See the SDL_GetWindowSurface()
docs (emphasis mine):
Get the SDL surface associated with the window.
A new surface will be created with the optimal format for the window, if necessary. This surface will be freed when the window is destroyed. Do not free this surface.
This surface will be invalidated if the window is resized. After resizing a window this function must be called again to return a valid surface.
You may not combine this with 3D or the rendering API on this window.
This function is affected by
SDL_HINT_FRAMEBUFFER_ACCELERATION
.