Programmatically add Gradient with solid color and

2019-07-07 02:06发布

问题:

Currently I am using this code to add color:

ShapeDrawable drawable = new ShapeDrawable(new OvalShape());
drawable.getPaint().setColor(color);

Now I need to apply some gradient colors to it along with stroke(like border with different color). I am setting this as background to button.

Here is what I am expecting, I need to do it programmatically.

回答1:

Add a RadialGradient to your drawable like this:

Shader shader = new RadialGradient(x, y, radius, color0, color1, Shader.TileMode.REPEAT);
drawable.getPaint().setShader(shader);

Obviously, you can interchange LinearGradient, SweepGradient, and any of the parameters.

Here is how to add the stroke:

drawable.getPaint().setStrokeWidth(3);
drawable.getPaint().setColor(Color.WHITE);
drawable.getPaint().setStyle(Paint.Style.FILL_AND_STROKE);

Hmmm, I think I have to defer to @StinePike with the GradientDrawable:

GradientDrawable gd = new GradientDrawable();
gd.setColor(Color.RED);
gd.setCornerRadius(10);
gd.setStroke(2, Color.WHITE);
gd.setShape(GradientDrawable.OVAL);


回答2:

use GradientDrawable to create gradient

or

you can see this answer