问题
Hi I would like to know if it is possible to simply take a screenshot with SDL2.
I tried SDL_GetWindowSurface
but I get an error saying:
No hardware accelerated renderers available.
I took the code from here.
Another solution I thought about is converting a texture to a surface but I didn't manage to do so...
Do you have any solution?
回答1:
It seems like you are mixing the rendering systems. That method will only work in the context of software rendering. For hardware rendering you should use the method SDL_RenderReadPixels()
. To save the screenshot you would need a code like that:
SDL_Surface *sshot = SDL_CreateRGBSurface(0, w, h, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000);
SDL_RenderReadPixels(renderer, NULL, SDL_PIXELFORMAT_ARGB8888, sshot->pixels, sshot->pitch);
SDL_SaveBMP(sshot, "screenshot.bmp");
SDL_FreeSurface(sshot);
Where w and h are the screen width and height (you can get these values using SDL_GetRendererOutputSize()
).
回答2:
In C SDL2 version 2.0.3, it works with:
fenetre=SDL_GetWindowFromId(touche.windowID); // "touche" is a SDL_KeyboardEvent, "fenetre" is a SDL_window pointer
r_copie=SDL_GetRenderer(fenetre);
s_SnapSource=SDL_CreateRGBSurface(0,SCREEN_WIDTH,SCREEN_HEIGHT,32,
rmask,
gmask,
bmask,
amask); // s_SnapSource is a SDL_Surface pointer
SDL_LockSurface(s_SnapSource);
SDL_RenderReadPixels(r_copie,NULL,s_SnapSource->format->format,
s_SnapSource->pixels,S_SnapSource->pitch);
SDL_SaveBMP(s_SnapSource,NomFichier); // NomFichier is a char*
SDL_UnlockSurface(s_SnapSource);
SDL_FreeSurface(s_SnapSource);
/!\ ATTENTION /!\
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
Uint32 rmask = 0xff000000;
Uint32 gmask = 0x00ff0000;
Uint32 bmask = 0x0000ff00;
Uint32 amask = 0x000000ff;
#else
Uint32 rmask = 0x000000ff;
Uint32 gmask = 0x0000ff00;
Uint32 bmask = 0x00ff0000;
Uint32 amask = 0xff000000;
#endif
...must previously be set somewhere (in a .h file for example)
EDIT: corrections needed
Don't put the previous paragraph in .h file, cause it may lead to a multiple definition of the variables *mask... if you use multiple source files in a project... put this in a function implementation instead...
来源:https://stackoverflow.com/questions/22315980/sdl2-c-taking-a-screenshot