Skip to content

Instantly share code, notes, and snippets.

@c272
Created June 28, 2018 09:54
Show Gist options
  • Save c272/174e8fdcd08634ff83af95e9eda70595 to your computer and use it in GitHub Desktop.
Save c272/174e8fdcd08634ff83af95e9eda70595 to your computer and use it in GitHub Desktop.
Loading .PNG in SDL2 in 78 lines.
//Including SDL and standard headers.
//Note that you'll have to include all the libraries and include paths,
//and on Windows include a copy of SDL.dll and SDL_image.dll in the application directory.
#include <SDL.h>
#include <SDL_image.h>
#include <stdio.h>
#include <string>
//Predefining functions/variables.
SDL_Surface* loadPNGSurface(std::string);
SDL_Window* window = NULL;
SDL_Surface* window_surf = NULL;
SDL_Surface* loaded_surf = NULL;
//Spinning up surface in main.
int main(int argc, char* argv[]) {
//Initializing SDL.
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
printf("Error: Could not initialise SDL.");
}
else {
//Loading the window.
window = SDL_CreateWindow("PNG Loading Test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, SDL_WINDOW_SHOWN);
//Loading the surface from said window.
window_surf = SDL_GetWindowSurface(window);
//Initializing PNG processing.
if (IMG_Init(IMG_INIT_PNG) < 0) {
printf("Error: Failed to load PNG processing.");
}
//Now testing PNG loading onto surfaces!
loaded_surf = loadPNGSurface("img/test.png");
//Scaling and updating window.
SDL_Rect window_rect;
window_rect.x = 0;
window_rect.y = 0;
window_rect.w = 800;
window_rect.h = 600;
SDL_BlitScaled(loaded_surf, NULL, window_surf, &window_rect);
SDL_UpdateWindowSurface(window);
//Waiting for quit.
bool quit = false;
SDL_Event e;
while (!quit) {
while (SDL_PollEvent(&e) != 0) {
//Checking for quit flag.
if (e.type == SDL_QUIT) {
quit = true;
}
}
}
}
return 0;
}
//Function for loading PNG/other image files.
SDL_Surface* loadPNGSurface(std::string path) {
//Creating final surface.
SDL_Surface* loadedSurf;
//Loading file to surface.
loadedSurf = IMG_Load(path.c_str());
if (loadedSurf == NULL) {
printf("Error: Failed to load texture %s.", path);
}
//Optimizing surface.
SDL_Surface* finalSurf = SDL_ConvertSurface(loadedSurf, window_surf->format, NULL);
//Freeing unoptimised surface, returning.
SDL_FreeSurface(loadedSurf);
return finalSurf;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment