SDL2: Renderer vs Surface
What is the difference between an SDL_Renderer and an SDL_Surface in SDL2?
In SDL2, SDL_Renderer and SDL_Surface are two different ways to render graphics, each with its own use cases and advantages.
SDL_Surface
An SDL_Surface is a pixel buffer that represents an image in memory. It contains the pixel data and format information. You can manipulate the pixels directly and perform software-based rendering using an SDL_Surface.
Here's an example of creating an SDL_Surface and filling it with a solid color:
SDL_Surface* surface{SDL_CreateRGBSurface(
0, width, height, 32, 0, 0, 0, 0)};
SDL_FillRect(surface, nullptr, SDL_MapRGB(
surface->format, 255, 0, 0));SDL_Renderer
An SDL_Renderer is a rendering context that provides hardware-accelerated 2D rendering. It abstracts the rendering process and allows you to draw primitives, textures, and perform transformations efficiently.
Here's an example of creating an SDL_Renderer and drawing a rectangle:
SDL_Renderer* renderer{SDL_CreateRenderer(
window, -1, 0)};
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
SDL_RenderClear(renderer);
SDL_Rect rect = {100, 100, 200, 150};
SDL_RenderFillRect(renderer, &rect);
SDL_RenderPresent(renderer);Differences and Use Cases
SDL_Surfaceis suitable for software rendering and direct pixel manipulation, whileSDL_Rendererprovides hardware-accelerated rendering.SDL_Surfaceis generally slower for rendering compared toSDL_Rendererbut offers more low-level control over pixels.SDL_Rendereris preferred for efficient rendering of complex graphics, such as textures, primitives, and transformations.SDL_Surfacecan be converted to a texture usingSDL_CreateTextureFromSurfacefor rendering with anSDL_Renderer.
In most cases, using SDL_Renderer is recommended for better performance and modern rendering techniques. However, SDL_Surface is still useful for specific tasks like pixel-level manipulations or software-based rendering algorithms.
Building SDL2 from Source (GCC and Make)
This guide walks you through the process of compiling SDL2, SDL_image, and SDL_ttf libraries from source