I'm using SDL2 and I have the following code:
#include <iostream>
#include <SDL2/SDL.h>
const int WIDTH = 800, HEIGHT = 600;
int main (int argc, char *argv[]){
SDL_Init(SDL_INIT_EVERYTHING);
SDL_Window *window = SDL_CreateWindow("Test", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WIDTH, HEIGHT, SDL_WINDOW_ALLOW_HIGHDPI);
if (NULL == window){
std::cout << "Could not create window. ERR_MSG: " << SDL_GetError() << std::endl;
return 1;
}
// Actual code begins here
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0);
SDL_RenderClear(renderer);
SDL_Rect rect;
rect.x = WIDTH/2;
rect.y = HEIGHT/2;
rect.w = 250;
rect.h = 250;
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderDrawRect(renderer, &rect);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderPresent(renderer);
// Actual code ends here
SDL_Event windowEvent;
while (true){
if (SDL_PollEvent( &windowEvent)){
if (SDL_QUIT == windowEvent.type){
break;
}
}
}
// destroy the window after the while loop is broken
SDL_DestroyWindow(window);
SDL_Quit();
return EXIT_SUCCESS;
}
which essentially finds the half of the width and height of the window to render a simple rectangle at the centre of the screen. However, I don't seem to get my desired result:
As you can see, the rectangle is not positioned at the centre. Can anyone help? Is there a function that centres the rectangle automatically (and ideally even if the window is resized)?
I've tried dividing the width and height with multiple integers, and also tried to implement this solution on stack overflow:
SDL_Rect: What is the formula to get a rectangle in the center of the screen?
The first approach didn't give me the desired result and the second one just resulted in a compiler error.
The coordinates you provide for drawing the rectangle designate the top left corner. If you want the center of the rectangle at the center of the screen, then simply subtract half the rectangles width from the x coordinate and half its height from the y coordinate.