I want to create a nine patch button background with a gradient for my android app. I was wondering how gradients work. I would think that the os would have to figure out how to apply the gradient as the button stretched and I'm guessing that information (a graphic vector equation) is not available in the 9 patch file? So is there a solution for this problem? Also, what about dithering, etc. I have created a few nine-patch button backgrounds, but none of them have a gradient. yet. Thanks in advance.
2 Answers
Why do you want to use a 9-patch for that? 9-patches stretch an area of an image by copying/duplicating pixels. That will not work well with gradients. Have you considered using a GradientDrawable instead?
<shape android:shape="rectangle">
<gradient android:startColor="..." android:endColor="..." />
</shape>
See shape drawables.

- 43,056
- 28
- 105
- 132
-
I would use a GradientDrawable but this is a shape drawable is only good for a ovals, ellipses, rectangles, etc. and not usable for any arbitrary shape like a nine-patch .png would be? Maybe use some kind of Layer List? Thanks. – Mike Mar 02 '11 at 05:14
-
You would want to use a 9 patch because you have more control and it will work well with a top to bottom gradient that gets stretched in width. You can for example have a different border color on the top of the button vs the bottom (iPhone buttons are like this). Or you could have different kinds of shapes. But its not a perfect fit for everything. See this link for discussion and example: http://www.anddev.org/tutorial_buttons_with_niceley_stretched_background-t4369.html – Fraggle Nov 22 '11 at 23:24
As to your question about dithering, I didn't address that with my previous reply.
You'll have to enable dithering from your application code I'm afraid, as far as I know there is no way to do it from XML. You can use the setDither(true)
call on your drawable, as documented here.
This will make for much nicer gradients, since it mitigates the banding artifacts you see on gradient images. I haven't tried this on shape drawables though, just PNG files.
Also, if you're targeting Gingerbread it may be worth reading Bitmap quality, banding and dithering. Apparently they snuck a change into 2.3 which addresses these issues.

- 43,056
- 28
- 105
- 132
-
1I have `
`s with the `android:dither="true"` attribute, so it at least is legal; not that I've checked (recently) that it does indeed function. – Christopher Orr Feb 28 '11 at 18:45