When your SDL2 window is resized, you'll need to adjust your rendering to fit the new window size. This involves handling the SDL_WINDOWEVENT
event and checking for the SDL_WINDOWEVENT_RESIZED
event type. Here’s how to set it up:
#include <SDL.h>
#include <iostream>
int main(int argc, char** argv) {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window = SDL_CreateWindow(
"Resize Example", 100, 100, 640, 480,
SDL_WINDOW_RESIZABLE);
SDL_Renderer* renderer = SDL_CreateRenderer(
window, -1, SDL_RENDERER_ACCELERATED);
bool running = true;
SDL_Event event;
while (running) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT)
running = false;
if (event.type == SDL_WINDOWEVENT &&
event.window.event ==
SDL_WINDOWEVENT_RESIZED) {
std::cout << "Window resized to "
<< event.window.data1 << "x"
<< event.window.data2 << "\n";
SDL_RenderSetLogicalSize(renderer,
event.window.data1, event.window.data2);
}
}
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
// Rendering code here
SDL_RenderPresent(renderer);
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
Window resized to 694x541
Window resized to 694x541
The above code updates the renderer to match the new window size whenever it is resized, ensuring that the rendering area remains consistent with the window dimensions.
Answers to questions are automatically generated and may not have been reviewed.
Step-by-step guide on creating the SDL2 application and event loops for interactive games