Creating the Main Loop with SDL2

Handling Window Resize Events in SDL2

How do I handle window resize events in SDL2 to adjust my rendering?

Abstract art representing computer programming

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.

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 27 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved