Sunny
Sunny

Reputation: 7604

mixing two gradient drawable for a view in android

I am trying to draw some colors in the background of a view.

The colors are to be placed as linear gradients and in different directions.

So i did the following:

private Orientation[] orientations = new Orientation[]{Orientation.BL_TR, Orientation.BR_TL, Orientation.TL_BR, Orientation.TR_BL, Orientation.TOP_BOTTOM};    
public void drawBackgroudGradient(RelativeLayout backgroundView, int[] colors){
        if (colors != null){
            if (colors.length > 1){
                for (int i=0; i<colors.length; i++){
                    backgroundView.setBackgroundDrawable(getGradientDrawable(colors[i], orientations[i]));
                }
            }else{
                //in case of only one color just set that color as background
                    backgroundView.setBackgroundColor(colors[0]);
            }
        }
    }

    private GradientDrawable getGradientDrawable(int color, Orientation orientation){
        int[] colors = new int[] {color, Color.WHITE};

        GradientDrawable drawable = new GradientDrawable(orientation, colors);
        drawable.setAlpha(125);
        return drawable;
    }

I have each drawable going from the starting color to transparent so that all the gradients are visible. But the problem is that all the colors are not showing up. Only the last color is drawn via the gradient drawable. the rest can not be seen.

Could someone please help me figure out how to mix and show all the colors?

Thanks. Sunny

Upvotes: 0

Views: 1136

Answers (1)

Ehsan Jelodar
Ehsan Jelodar

Reputation: 1544

create LayerDrawable and mix them:

    private LayerDrawable getGradientDrawable(int color, Orientation  orientation){
    int[] colors = new int[] {color, Color.WHITE};

    GradientDrawable drawable1 = new GradientDrawable(orientation, colors);
    drawable1.setAlpha(125);

    GradientDrawable drawable2 = new GradientDrawable();
    drawable2.setStroke(4, Color.parseColor("#FFFFFF"));
    drawable2.setColor(Color.TRANSPARENT);

    return new LayerDrawable(new Drawable[]{drawable1 , drawable2});

}

drawable2 placed on top of drawable1.

Upvotes: 2

Related Questions