Skip to content

Instantly share code, notes, and snippets.

@rdeioris
Created November 7, 2017 10:30
Show Gist options
  • Save rdeioris/65836fc597ac5dfec906428af3173c6a to your computer and use it in GitHub Desktop.
Save rdeioris/65836fc597ac5dfec906428af3173c6a to your computer and use it in GitHub Desktop.
Draw a texture with SDL2
#define SDL_MAIN_HANDLED
#ifdef _WIN32
#include <SDL.h>
#else
#include <SDL2/SDL.h>
#endif
#include <stdio.h>
int main(int argc, char* argv[]) {
SDL_Window *win = NULL;
SDL_Renderer *renderer = NULL;
SDL_Texture *bitmapTex = NULL;
SDL_Surface *bitmapSurface = NULL;
int posX = 100, posY = 100, width = 320, height = 240;
SDL_Rect rect;
rect.x = 100;
rect.y = 100;
rect.w = 200;
rect.h = 100;
SDL_Init(SDL_INIT_VIDEO);
win = SDL_CreateWindow("Hello World", posX, posY, width, height, 0);
if (!win)
{
fprintf(stderr,"ERROR: %s\n", SDL_GetError());
return -1;
}
renderer = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);
if (!renderer)
{
goto error0;
}
bitmapSurface = SDL_LoadBMP("face.bmp");
if (!bitmapSurface)
{
goto error1;
}
bitmapTex = SDL_CreateTextureFromSurface(renderer, bitmapSurface);
SDL_FreeSurface(bitmapSurface);
// postpone rollbacking to allow freeing the surface
if (!bitmapTex)
goto error2;
while (1) {
SDL_Event e;
if (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
break;
}
}
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, bitmapTex, NULL, &rect);
SDL_RenderPresent(renderer);
}
error2:
SDL_DestroyTexture(bitmapTex);
error1:
SDL_DestroyRenderer(renderer);
error0:
SDL_DestroyWindow(win);
SDL_Quit();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment