5

I am trying to create nine patch images programmatically. I have tried Griffey's approach but can't seem to get it to work. There is very little information about how to use the class. I believe I am importing the bitmap incorrectly. If anyone knows how to get this to work or knows a better way, I'd greatly appreciate your help.

My code:

// Dynamically create the 9patch image and apply it to a LinearLayout
LinearLayout llcode = (LinearLayout) findViewById(R.id.llcode);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.white_button);
Drawable np = NinePatchBitmapFactory.createNinePathWithCapInsets(getResources(), bitmap, 15, 15, 16, 16, null);

llcode.setBackgroundDrawable(np);

// The following code using the actual 9patch image: white_button_np.9.png
LinearLayout llxml = (LinearLayout) findViewById(R.id.llxml);
llxml.setBackgroundDrawable(getResources().getDrawable(R.drawable.white_button_np));

This screenshot shows the programmatic method on top and the typical 9patch method using the android tool on bottom.

enter image description here

The original image before it's converted to a 9patch.

enter image description here

Community
  • 1
  • 1
Brendan
  • 71
  • 1
  • 2
  • 1
    After some more testing I have discovered that the error above is only happening in older phones and all emulators. I tested on a Galax Nexus running 4.1.2 and Griffey's class worked fine. I tested on a Droid X running 2.3.4 and all emulators (including a Galaxy Nexus-4.1.2) and the LinearLayout had varying strange colors like the screenshot above. – Brendan Jan 21 '13 at 22:01
  • I'm also stuck on this one, did you find a way to solve it? – Nativ Nov 13 '13 at 13:42
  • I've tested this with buttons with emulators. In API level 10 it seems to be broken, but in API level 16 it works OK for me. – Scorchio Jan 20 '14 at 12:30
  • Hey guys! When developing that gist Romain Guy had informed me that this solution is probably not stable across all version of Android because the NinePatch format is subject to change. Sorry for the inconvenience, I'll note this in the gist. – Brian Griffey Jan 20 '14 at 15:49

2 Answers2

0

Have you tried forcing the decoder configuration to make sure there's an alpha channel?

Try setting inPreferredConfig to ARGB_8888.

Chris Banes
  • 31,763
  • 16
  • 59
  • 50
0

The solution is here: https://stackoverflow.com/a/16676419/238845. I've tested it successfully on the API level 10 emulator.

Community
  • 1
  • 1
Scorchio
  • 2,763
  • 2
  • 20
  • 28