Search code examples
androidnine-patch

Understanding 9-patch drawables


Part 1

If 9-patch images must have a one pixel stretchable area for regions 2, 4, 6, 8 (counting the areas in reading order), how can 9-patch images capture an image such as the one below, where the corners are 4x4, and each of the stretchable areas is 4-pixels wide?

9-patch

Part 2

Why does sdk/tools/draw9patch make it possible to modify the top and bottom areas independently? Likewise, why are the left and right areas independent? I would be expecting the editor to provide the means to manipulate just the four carets that appear in the image above.


Solution

  • The 4 borders must be 1px tall (or wide) and transparent.
    They may or may not have the 9 patch markers 1 px tall (or wide) and tall and black.

    The top border is used to mark (zero), one or more stretchable horizontal area/s.
    The left border is used to mark (zero), one or more stretchable vertical area/s.

    The (optional) right border is used to set the vertical content area (in practice, it marks some internal padding).
    The (optional) bottom border is used to set the horizontal content area (in practice, it marks some internal padding).

    More is found in this article: http://blog.booleanbites.com/2012/11/android-how-to-use-9-patch-png.html

    For example

    Either of the following two images is suitable as a 9-patch, subject to the following constraints:

    1. The quarter-circles at the four corners must maintain their aspect ratio, even if the aspect ratio of the image is modified from its original.
    2. Likewise the circles in the border must remain circles (i.e., they may not be scaled).

    Also:

    The specification of 9-patch images is under-constrained, namely:

    1. Nothing is specified regarding the four green corners. They can have any value.
    2. Since we specify the zones that will be scaled when needed, rather those that may not be scaled, there is leeway in the specification of the pink single-pixel borders. Either the top or the bottom will do. However, in this example, to maintain the circles in the center of the borders, the width of the pink pixels must be equal.

    In this example we look specifically at the case where the intention is to create a variable-sized frame. For this to work as intended the transparency must be set correctly:

    1. The transparency of the inner grey region is full-transparent.
    2. The transparency of the pink pixels is irrelevant (?).
    3. The transparency of the cyan pixels must be full opaque.

    9-patch frame example