Search code examples
androidlayoutpaddingnine-patch

Hide a 1px margin when displaying a png


I am receiving nine-patch images from a server to display in the ui of my android app. This is a hard requirement so I am unable to compile the nine-patches into the APK. It appears that Android will recognize and display any PNG as a nine-patch, meaning the stretching of the image follows the outline indicated by the outer pixel. The problem is that Android still displays the 1px boundary of the file. So I have attempted to set the padding on the View to -1 so that line is not displayed. This does not appear to work since the black lines are still showing.

    <ImageView
        android:id="@+id/stub_image"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="centerCrop"
        android:padding="-1px"
        android:cropToPadding="true"
        android:src="@drawable/stub_image"
        android:contentDescription="@string/image_title" />

How can I set this layout to NOT show a 1px boundary around a PNG? Can I do this without overriding the View class and manually mucking around with pixels?

SOLUTION

Following the first option on the post @alex linked to, I am compiling the ninepatch files in an otherwise empty solution. Those are then provided to the app from my server. Since png's are possibly sent by the server, as well as ninepatches, the code I use to obtain the drawable is as follows:

InputStream stream = .. //whatever
Bitmap bitmap = BitmapFactory.decodeStream(stream);
byte[] chunk = bitmap.getNinePatchChunk();
if (NinePatch.isNinePatchChunk(chunk)) {
    return new NinePatchDrawable(getResources(), bitmap, chunk, new Rect(), null);
} else {
    return new BitmapDrawable(getResources(), bitmap);
}

Solution

  • Use a NinePatchDrawable to parse the Bitmap so it's displayed properly.