25

I'm trying to draw a nine patch onto a Canvas object on the Android. What seems strange is that although I generated my nine patch using the draw9patch tool, the constructor for NinePatch requires an additional byte array called the "chunk" to construct the nine patch.

Why isn't this simpler? What is the "chunk"? And if you have done this yourself, how did you go about it?

Any help appreciated.

Tom R
  • 5,991
  • 9
  • 35
  • 41

1 Answers1

79

You can easily do it this way:

// Load the image as a NinePatch drawable
NinePatchDrawable npd = (NinePatchDrawable)Resources.getDrawable(R.drawable.my_nine_patch);

// Set its bound where you need
Rect npdBounds = new Rect(...);
npd.setBounds(npbBounds);

// Finally draw on the canvas
npd.draw(canvas);
marzapower
  • 5,531
  • 7
  • 38
  • 76
Mark B
  • 183,023
  • 24
  • 297
  • 295
  • 1
    But I need the image to fit a specific size. Otherwise I wouldn't use a nine-patch. – Tom R Jan 24 '10 at 17:07
  • 7
    In the code I put in above, the object 'd' is actually an instance of NinePatchDrawable since you gave getDrawable the ID of a 9patch resource. So you could do NinePatchDrawable npd = (NinePatchDrawable) d; Will that not work for your purposes? – Mark B Jan 24 '10 at 17:49
  • 35
    Casting it is not necessary, but you need to call setBounds() on the Drawable before drawing it. – Romain Guy Jan 25 '10 at 00:52
  • Brilliant, I could not find this anywhere in the docs. Thank you so much. – Rickard Lindroth Sep 15 '10 at 12:55