Permalink
Browse files

Add ability to take screenshot of the window

  • Loading branch information...
blacktm committed Dec 11, 2018
1 parent 16ecfff commit bddf08c74fb4e90f703db522806c6493fb3e5374
Showing with 47 additions and 0 deletions.
  1. +1 −0 .gitignore
  2. +5 −0 include/simple2d.h
  3. +40 −0 src/window.c
  4. +1 −0 test/testcard.c
@@ -7,3 +7,4 @@ test/testcard
test/audio
test/controller
test/*.exe
test/screenshot.png
@@ -641,6 +641,11 @@ int S2D_Show(S2D_Window *window);
*/
void S2D_SetIcon(S2D_Window *window, const char *icon);

/*
* Take a screenshot of the window
*/
void S2D_Screenshot(S2D_Window *window, const char *path);

/*
* Close the window
*/
@@ -335,6 +335,46 @@ void S2D_SetIcon(S2D_Window *window, const char *icon) {
}


/*
* Take a screenshot of the window
*/
void S2D_Screenshot(S2D_Window *window, const char *path) {

// Create a surface the size of the window
SDL_Surface *surface = SDL_CreateRGBSurface(
SDL_SWSURFACE, window->width, window->height, 24,
0x000000FF, 0x0000FF00, 0x00FF0000, 0
);

// Grab the pixels from the front buffer, save to surface
glReadBuffer(GL_FRONT);
glReadPixels(0, 0, window->width, window->height, GL_RGB, GL_UNSIGNED_BYTE, surface->pixels);

// Flip image vertically

void *temp_row = (void *)malloc(surface->pitch);
if (!temp_row) {
S2D_Error("S2D_Screenshot", "Out of memory!");
SDL_FreeSurface(surface);
return;
}

int height_div_2 = (int) (surface->h * 0.5);

for (int index = 0; index < height_div_2; index++) {
memcpy((Uint8 *)temp_row,(Uint8 *)(surface->pixels) + surface->pitch * index, surface->pitch);
memcpy((Uint8 *)(surface->pixels) + surface->pitch * index, (Uint8 *)(surface->pixels) + surface->pitch * (surface->h - index-1), surface->pitch);
memcpy((Uint8 *)(surface->pixels) + surface->pitch * (surface->h - index-1), temp_row, surface->pitch);
}

free(temp_row);

// Save image to disk
IMG_SavePNG(surface, path);
SDL_FreeSurface(surface);
}


/*
* Close the window
*/
@@ -37,6 +37,7 @@ void on_key(S2D_Event e) {
printf("Key down: %s\n", e.key);
if (strcmp(e.key, "Escape") == 0) S2D_Close(window);
if (strcmp(e.key, "R") == 0) rotate = rotate ? false : true;
if (strcmp(e.key, "S") == 0) S2D_Screenshot(window, "./screenshot.png");
break;

case S2D_KEY_HELD:

0 comments on commit bddf08c

Please sign in to comment.