To center an image on the screen using SDL2, we need to calculate the appropriate x and y coordinates for our destination rectangle. Here's how we can do it:
Let's see this in action:
#include <SDL.h>
#include <iostream>
class Image {
public:
Image(const char* file) : surface{
SDL_LoadBMP(file)} {
if (!surface) {
std::cerr << "Failed to load image: " <<
SDL_GetError() << '\n';
}
}
void RenderCentered(
SDL_Surface* destSurface) {
if (!surface || !destSurface) return;
int windowWidth = destSurface->w;
int windowHeight = destSurface->h;
int imageWidth = surface->w;
int imageHeight = surface->h;
// Calculate center position
int x = (windowWidth - imageWidth) / 2;
int y = (windowHeight - imageHeight) / 2;
SDL_Rect destRect{
x, y, imageWidth, imageHeight};
SDL_BlitSurface(surface, nullptr,
destSurface, &destRect);
}
private:
SDL_Surface* surface;
};
int main() {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window =
SDL_CreateWindow("Centered Image",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
640, 480, 0);
SDL_Surface* screenSurface =
SDL_GetWindowSurface(window);
Image img{"example.bmp"};
img.RenderCentered(screenSurface);
SDL_UpdateWindowSurface(window);
SDL_Delay(3000); // Display for 3 seconds
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
In this example, we've created an Image
class with a RenderCentered()
method. This method calculates the center position based on the window size and image size, then uses these coordinates in the destination rectangle for SDL_BlitSurface()
.
The key lines are:
int x = (windowWidth - imageWidth) / 2;
int y = (windowHeight - imageHeight) / 2;
These calculate the top-left corner coordinates that will place the image at the center of the screen.
Remember to handle potential errors, such as failing to load the image or create the window. Also, in a real application, you'd typically render in a loop rather than using SDL_Delay()
.
Answers to questions are automatically generated and may not have been reviewed.
Learn to precisely control image display using source and destination rectangles.