Drawing Rectangle Outlines in SDL2
How do I draw just the outline of a rectangle instead of filling it?
The function we used in this lesson, SDL_FillRect()
, is specifically designed to draw a solid, filled rectangular area on an SDL_Surface
. It does not have an option to draw only the border.
To draw the outline (or "wireframe") of a rectangle, you need to use different techniques or functions, depending on whether you are working directly with SDL_Surface
objects or the SDL_Renderer
approach.
Using SDL_Renderer
Renderers provide hardware-accelerated drawing capabilities and have specific functions for shapes:
- Set the Draw Color: Use
SDL_SetRenderDrawColor()
to select the color you want for the outline. - Draw the Rectangle Outline: Use
SDL_RenderDrawRect()
orSDL_RenderDrawRects()
passing the renderer and a pointer to yourSDL_Rect
, orSDL_FRect
withSDL_RenderDrawRectF()
.
// Conceptual example assuming 'renderer' is a valid SDL_Renderer*
// and 'rect' is an SDL_Rect
// Set draw color to white
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
// Draw the outline of the rectangle
SDL_RenderDrawRect(renderer, &rect);
// Remember to present the renderer
SDL_RenderPresent(renderer);
Working with SDL_Surface
Drawing outlines directly onto an SDL_Surface
(like the window surface obtained via SDL_GetWindowSurface()
) without a renderer is less direct. There isn't a single, built-in function equivalent to SDL_RenderDrawRect()
for surfaces. Common approaches include:
- Drawing Four Lines: Manually calculate the coordinates of the four corners and draw four individual lines connecting them using line-drawing algorithms or functions (SDL has
SDL_RenderDrawLine()
, but again, that's for renderers; for surfaces, you might need to implement line drawing or use a helper library). - Using Helper Libraries: Libraries built on top of SDL might provide functions for drawing shape outlines onto surfaces.
- Manual Pixel Plotting: For ultimate control, you could write code to directly manipulate the surface's pixels to draw the outline, but this is complex.
Later in the course, we learn how to draw rectangular outlines using the four-lines method.
Rectangles and SDL_Rect
Learn to create, render, and interact with basic rectangles using the SDL_Rect
and SDL_Color
types.