SDL2_image for Android with PNG image format

In the previous article, we were discussing how to add support for XPM image format to SDL2 application for Android. Let’s add other more common format. What about Portable Network Graphic (a.k.a. PNG)?

The first step is to enable PNG in SDL2_image. Just add a proper define to SDL2_image/build.gradle.

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

Unfortunately, it’s not that simple. PNG support has a dependency on PNG library with a patch and PNG library has a dependency on ZIP library. In order to get PNG working you need to add these two C libraries into the project. The approach is the same like when adding SDL2_image. Each library is stored as a separate module in the directory with the same name like module name.

Register modules in settings.gradle:

include ':SDL2_image'
include ':png'
include ':zip'

Each module has it’s own build.gradle: png/build.gradle, zip/build.gradle.

You can verify compilation of the whole suite by following commands:

gradle :zip:distributeLib
gradle :png:distributeLib
gradle :SDL2_image:distributeLib

Libraries are ready. Now it’s necessary to add PNG file to the project. The location for graphic assets is app/src/main/assets.

Here is a sample code for loading and displaying PNG image:

SDL_Surface *loadedSurface = IMG_Load("smiley.png");
SDL_Texture *smileyTexture = SDL_CreateTextureFromSurface(renderer, loadedSurface);
SDL_RenderCopy(renderer, smileyTexture, NULL, NULL);

Result looks like this:

As you can see the PNG version of smiley has support for background transparency.

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.

No votes yet.
Please wait...

9. July 2017 at 14:50 - Development (Tags: , , , , ).