Using a gradientDrawable with more than three colors set

android developer picture android developer · Dec 24, 2012 · Viewed 16.7k times · Source

According to what I've read, you can use a gradientDrawable and have three colors set for it, for example:

<gradient startColor="#00FF00" centerColor="#FFFF00" endColor="#FFFFFF"/>

But what if I want more than three colors, and not only that, I want to be able to set where to put each (in weight/percentage)?

Is it possible using the API or should I make my own customized drawable? If I need to make my own customized drawable, how should I do it?

Answer

Bhaskar picture Bhaskar · Feb 12, 2013

put this code in your onCreate() method:

ShapeDrawable.ShaderFactory shaderFactory = new ShapeDrawable.ShaderFactory() {
    @Override
    public Shader resize(int width, int height) {
        LinearGradient linearGradient = new LinearGradient(0, 0, width, height,
            new int[] { 
                0xFF1e5799, 
                0xFF207cca, 
                0xFF2989d8, 
                0xFF207cca }, //substitute the correct colors for these
            new float[] {
                0, 0.40f, 0.60f, 1 },
            Shader.TileMode.REPEAT);
         return linearGradient;
    }
};
PaintDrawable paint = new PaintDrawable();
paint.setShape(new RectShape());
paint.setShaderFactory(shaderFactory);

and use this drawable as a background.

You can add more than three colors in xml also by creating layers. But in XML it is quite complicated.