No-frills SDL2: Basic graphics

This is part of a series of basic SDL examples, introduced here.

  1. Initialize SDL:

    SDL_Init(SDL_INIT_VIDEO);

  2. Create window, and bind a renderer to it:

    SDL_Window *window = SDL_CreateWindow("Title", 0, 0, 800, 600, SDL_WINDOW_SHOWN);
    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

  3. Load bitmap image, with its magenta background transparent:

    SDL_Surface *imageRaw = SDL_LoadBMP("image.bmp");
    SDL_SetColorKey(imageRaw, SDL_TRUE, 0xff00ff);
    SDL_Texture *image = SDL_CreateTextureFromSurface(renderer, imageRaw);
    SDL_FreeSurface(imageRaw);

  4. Draw stuff to the screen:

    // Clear renderer with a blue color
    SDL_SetRenderDrawColor(renderer, 24, 82, 161, 255);
    SDL_RenderClear(renderer);

    // Draw yellow rectangle
    SDL_SetRenderDrawColor(renderer, 255, 255, 0, 255);
    SDL_Rect rectangle = {200, 100, 50, 150};
    SDL_RenderFillRect(renderer, &rectangle);

    // Draw image
    SDL_Rect imageRect = {500, 150, 50, 50};
    SDL_RenderCopy(renderer, image, 0, &imageRect);

    // Copy renderer to window
    SDL_RenderPresent(renderer);

  5. Clean up:

    SDL_DestroyTexture(image);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
Advertisements

One thought on “No-frills SDL2: Basic graphics

  1. Pingback: No-frills SDL2 examples | Block Comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: