Difference Between SDL_Window
and SDL_Surface
in SDL2
What's the difference between an SDL_Window
and an SDL_Surface
?
Think of an SDL_Window
and an SDL_Surface
like a picture frame and the picture (or canvas) inside it.
SDL_Window
An SDL_Window
represents the operating system window itself. This includes things like:
- The window's border or frame.
- The title bar at the top.
- Minimize, maximize, and close buttons.
- Its position and size on the desktop.
It's the container that holds our application's visual output. We create it using SDL_CreateWindow()
. It handles interactions with the operating system's window manager, like moving, resizing, or iconifying the window. It doesn't directly contain pixel data for drawing.
// Creates the OS window container
SDL_Window* MyWindow = SDL_CreateWindow(
"My Application Window", // Title
SDL_WINDOWPOS_CENTERED, // Initial x position
SDL_WINDOWPOS_CENTERED, // Initial y position
640, // Width
480, // Height
SDL_WINDOW_SHOWN // Flags (e.g., make it visible)
);
SDL_Surface
An SDL_Surface
represents a collection of pixels in CPU memory. It's essentially a 2D array of color data that you can draw onto or manipulate directly. Key aspects include:
- A pointer to the actual pixel data.
- The dimensions (width and height) of the pixel grid.
- Information about how the colors are stored (the
SDL_PixelFormat
).
Surfaces are used for software rendering (drawing using the CPU). You can load images into surfaces, create blank surfaces to draw on, or get the special surface associated with a window for direct drawing.
// Get the surface associated with the
// window (for drawing)
SDL_Surface* WindowSurface{
SDL_GetWindowSurface(MyWindow)};
// Or, create a new, blank surface
// (e.g., for off-screen drawing)
SDL_Surface* MySurface{SDL_CreateRGBSurface(
0, // Flags (must be 0)
100, // Width
50, // Height
32, // Bits per pixel (e.g., 32 for RGBA8888)
0, 0, 0, 0 // Masks (can often be 0 for standard formats)
)};
// Remember to free surfaces you create manually
if (MySurface) {
SDL_FreeSurface(MySurface);
}
The Connection
The function SDL_GetWindowSurface()
provides the link: it returns the SDL_Surface
that acts as the drawing canvas for that specific SDL_Window
. When you draw on this particular surface and call SDL_UpdateWindowSurface()
, SDL copies the pixel data from that surface onto the actual window displayed by the OS.
So, SDL_Window
is the frame, and SDL_Surface
is the canvas inside (or any other canvas you might create in memory). You need the window to show things on the screen, and you need a surface to define what pixels to show.
SDL Surfaces and Colors
Explore SDL surfaces, the canvases for drawing, understand pixel formats, colors, and set your window's background.