SDL2_image for Android with XPM image format

In the previous article, we were discussing how to start building SDL2 application for Android. Let’s add some images.

SDL2 library does not contain support for any image formats, you have to add further library SDL2_image which has support for several formats.

In order to add SDL2_image into Android project it is necessary to add a new module to settings.gradle:

include ':SDL2_image'

The module itself will be stored in SDL2_image directory with build.gradle which contains reference to main SDL2 library:

model {
    repositories {
        libs(PrebuiltLibraries) {
            SDL2 {
                headers.srcDir "../SDL2/include"
                binaries.withType(SharedLibraryBinary) {
                    sharedLibraryFile = file("${lib_distribution_root}/SDL2/lib/${targetPlatform.getName()}/libSDL2.so")
                }
            }
        }
    }

SDL2_image has support for several formats. You need to turn them on based on your requirements. It’s easy, just add proper define to compiler. Let’s start with simplest format XPM:

ndk { 
...
   CFlags.addAll(["-DLOAD_XPM"])
...
}

X PixMap (or XPM) is very simple image format which could be embedded directly into the source code.

static char * icon_xpm[] = {
        "32 23 3 1",
        "     c #FFFFFF",
        ".    c #000000",
        "+    c #FFFF00",
        "                                ",
        "            ........            ",
        "          ..++++++++..          ",
        "         .++++++++++++.         ",
        "        .++++++++++++++.        ",
        "       .++++++++++++++++.       ",
        "      .++++++++++++++++++.      ",
        "      .+++....++++....+++.      ",
        "     .++++.. .++++.. .++++.     ",
        "     .++++....++++....++++.     ",
        "     .++++++++++++++++++++.     ",
        "     .++++++++++++++++++++.     ",
        "     .+++++++++..+++++++++.     ",
        "     .+++++++++..+++++++++.     ",
        "     .++++++++++++++++++++.     ",
        "      .++++++++++++++++++.      ",
        "      .++...++++++++...++.      ",
        "       .++............++.       ",
        "        .++..........++.        ",
        "         .+++......+++.         ",
        "          ..++++++++..          ",
        "            ........            ",
        "                                "}

The next step is to transform XPM from the source code into memory structure which could be rendered on the screen.

SDL_Surface *surface;
surface = IMG_ReadXPMFromArray(icon_xpm);
texture = SDL_CreateTextureFromSurface(renderer, surface);

The last part is to call render function. You can find whole source code at https://github.com/georgik/sdl2-android-example.

We will discuss how to use further SDL2 libraries in next articles. You can find more under topic SDL2.