Filling Only Part of an SDL_Surface
with SDL_FillRect()
What if I only want to fill part of the window surface using SDL_FillRect()
?
The SDL_FillRect()
function is designed to fill a rectangular area on a surface. While passing nullptr
for the rectangle argument fills the entire surface, you can specify a particular area by providing a pointer to an SDL_Rect
structure.
The SDL_Rect
Structure
An SDL_Rect
defines a rectangular area using four integer members:
x
: The x-coordinate of the top-left corner of the rectangle.y
: The y-coordinate of the top-left corner of the rectangle.w
: The width of the rectangle (in pixels).h
: The height of the rectangle (in pixels).
Remember that the coordinate system for surfaces usually starts with (0,0) at the top-left corner, with X increasing to the right and Y increasing downwards.
Using SDL_Rect
with SDL_FillRect()
To fill only a specific part of a surface, you need to:
- Create an
SDL_Rect
variable. - Set its
x
,y
,w
, andh
members to define the target area. - Pass the address (a pointer) of this
SDL_Rect
variable as the second argument toSDL_FillRect()
.
// Assume 'WindowSurface' is a valid SDL_Surface*
// (e.g., from SDL_GetWindowSurface)
// Assume 'format' is the SDL_PixelFormat*
// from WindowSurface->format
// Assume 'MyWindow' is the SDL_Window*
// 1. Define the rectangle area
SDL_Rect FillArea;
FillArea.x = 50; // 50 pixels from the left edge
FillArea.y = 100; // 100 pixels from the top edge
FillArea.w = 200; // 200 pixels wide
FillArea.h = 150; // 150 pixels tall
// 2. Define the color (Bright Green)
Uint32 FillColor = SDL_MapRGB(format, 0, 255, 0);
// 3. Call SDL_FillRect with the address of the SDL_Rect
SDL_FillRect(
WindowSurface, // The surface to draw on
&FillArea, // Pointer to the rectangle to fill
FillColor // The color to use
);
// 4. Update the window to see the change
SDL_UpdateWindowSurface(MyWindow);
This code would fill only a green rectangle within the specified coordinates (from x=50, y=100 to x=250, y=250) on the WindowSurface
, leaving the rest of the surface unchanged from its previous state.
We'll explore SDL_Rect
and coordinate systems in much more detail in later lessons, as they are fundamental to positioning graphics, handling collisions, and managing camera views.
SDL Surfaces and Colors
Explore SDL surfaces, the canvases for drawing, understand pixel formats, colors, and set your window's background.