Skip to content

Instantly share code, notes, and snippets.

@malja
Last active April 11, 2024 08:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malja/2193bd656fe50c203f264ce554919976 to your computer and use it in GitHub Desktop.
Save malja/2193bd656fe50c203f264ce554919976 to your computer and use it in GitHub Desktop.
Create screenshot in SDL2
// Save screenshot
// file: Filename for created screenshot
// renderer: pointer to SDL_Renderer
bool saveScreenshot(const std::string &file, SDL_Renderer *renderer ) {
// Used temporary variables
SDL_Rect _viewport;
SDL_Surface *_surface = NULL;
// Get viewport size
SDL_RenderGetViewport( renderer, &_viewport);
// Create SDL_Surface with depth of 32 bits
_surface = SDL_CreateRGBSurface( 0, _viewport.w, _viewport.h, 32, 0, 0, 0, 0 );
// Check if the surface is created properly
if ( _surface == NULL ) {
std::cout << "Cannot create SDL_Surface: " << SDL_GetError() << std::endl;
return false;
}
// Get data from SDL_Renderer and save them into surface
if ( SDL_RenderReadPixels( renderer, NULL, _surface->format->format, _surface->pixels, _surface->pitch ) != 0 ) {
std::cout << "Cannot read data from SDL_Renderer: " << SDL_GetError() << std::endl;
// Don't forget to free memory
SDL_FreeSurface(_surface);
return false;
}
// Save screenshot as PNG file
if ( IMG_SavePNG( _surface, file.c_str() ) != 0 ) {
std::cout << "Cannot save PNG file: " << SDL_GetError() << std::endl;
// Free memory
SDL_FreeSurface(_surface);
return false;
}
// Free memory
SDL_FreeSurface(_surface);
return true;
}
@fccm
Copy link

fccm commented Jun 3, 2019

Maybe

_surface-->pitch

should be

_surface->pitch

@malja
Copy link
Author

malja commented Jun 3, 2019

@fccm Thank you for pointing that out. ;) Corrected.

@HugoAndre276
Copy link

HugoAndre276 commented Jan 17, 2020

I get
dyld: Symbol not found: _SDL_RWwrite Referenced from: /Library/Frameworks/SDL2_image.framework/Versions/A/SDL2_image Expected in: /Library/Frameworks/SDL2.framework/Versions/A/SDL2
as an ouput

@malja
Copy link
Author

malja commented Jan 18, 2020

@HugoAndre276

Symbol not found: _SDL_RWwrite

I think it has something to do with a recent change in SDL library. They changed SDL_RW* macros to functions. All I have found is that now you have to link SDL2 library to your project.

Make sure you are using latest version of SDL2 and SDL_Image as well.

But I am not sure how to solve your problem, since I don't own mac or Xcode. Try contacting official forum. They might help you.

@afwn90cj93201nixr2e1re
Copy link

Any ready project's? For example with rect's and transparency?
It's .zip file.
ConsoleApplication

@malja

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment