viernes, octubre 11, 2013

Android 9-patch splash screens that do not stretch the logo in the middle

A common need for a mobile app is a splash screen (which typically fill the whole screen) that contains a logo and that adapts itself to different screen resolutions and form factors without distorting the logo.

Google has a PNG format called 9-patch that allows to stretch just the sides of an image for Android apps, as for a logo, or, else, just the center (for instance, a button whose inside stretches leaving the corners intact).

However, I took me quite a while to figure out how to create 9-patch images that leave a logo in the middle intact (which is probably not surprising with Google things, that tend to lean on the cryptic side).

You need to start with a PNG image with some room around the logo in the center, as Android is going to stretch the “margins” (fill), if you will.

Them, open it with draw9patch.exe, included in the Android SDK.

You can find general info easily on the web, but the trick here is that the TOP and LEFT lines delimit the margins, while the lines at the BOTTOM and RIGHT define the object in the middle.

It should be obvious from looking at the screen capture.

There is also an online utility called Simple Nine-patch Generator in Google's Asset Studio that should allow for the creating 9-patch versions of a number of sizes of a given image in one go, but it does not work for this case as it can only do a single “stretch regions”, although the logo itself can be selected appropriately with the “content padding” area. The new “Optical bounds” feature only works for Android 4.3+ and is used for aligning, which is not of use for a splash screen. So you should make the largest image in draw9patch and then generate the other sizes with 9patch-resizer.