• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Create NinePatch at runtime

Hello everybody!

I have a business need to create the NinePatchDrawable objects at runtime, this is, an exterior .png image is received from a server and it has to be applied in a button's background (for example) as a nine patch.

I have tried to create the NinePatchDrawable object, but the constructor asks me for a "byte[] chuck" that describes the patch. The thing is, I have no idea on how to build this chunck from a bitmap that does not have the 9patch information in it.

Any ideas on this topic? Am I seeing the problem from a wrong perpective?

Thanks!
 
The chunk data is normally created at compile time and not well documented. I was trying to do something similar to you and tried pulling the chunk data out of an existing nine-patch and then applying it to the loaded image (the loaded image didn't include any 9-patch borders)

Pretty hacky and requires the new image be the exact same size as the original and stretch at the same points. (minus 9-patch borders). I didn't end up using this code for production for a couple of reasons.

Code:
NinePatchDrawable npd = (NinePatchDrawable) origd;
Field field;
                        try {
                            field = NinePatchDrawable.class.getDeclaredField("mNinePatch");
                            field.setAccessible(true);
                            NinePatch np = (NinePatch) field.get(npd);
                            field = NinePatch.class.getDeclaredField("mBitmap");
                            field.setAccessible(true);
                            Bitmap b = (Bitmap) field.get(np);
                            field = NinePatch.class.getDeclaredField("mChunk");
                            field.setAccessible(true);
                            chunk = (byte[]) field.get(np);
                        } catch (SecurityException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (NoSuchFieldException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IllegalArgumentException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
 
Back
Top Bottom