7

Hi I want to create a shape drawable and fill it with gradient color with white stroke here is my code

    ShapeDrawable greenShape = new ShapeDrawable(new RectShape());
    Shader shader1 = new LinearGradient(0, 0, 0, 50, new int[] {
            0xFFBAF706, 0xFF4CD52F  }, null, Shader.TileMode.CLAMP);
    greenShape.getPaint().setShader(shader1);
    greenShape.getPaint().setStrokeWidth(3);
    greenShape.getPaint().setColor(Color.WHITE);
    greenShape.getPaint().setStyle(Paint.Style.FILL_AND_STROKE);`

The problem is the rectangle appears with gradient fill but without stroke

JustMe
  • 10,033
  • 5
  • 20
  • 12

4 Answers4

14

The ShapeDrawable does not allow you to easily draw a stroke around it. If you really want then this would be a nice place to look at.

OR

You could use a GradientDrawable

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

(PS: This is given as a comment in the same page!)

ItamarG3
  • 4,092
  • 6
  • 31
  • 44
Sree Aurovindh
  • 705
  • 1
  • 6
  • 18
2

It looks like this person struggled with the same issue and the only way they found was to subclass the ShapeDrawable:

Trying to draw a button: how to set a stroke color and how to "align" a gradient to the bottom without knowing the height?

Community
  • 1
  • 1
CaseyB
  • 24,780
  • 14
  • 77
  • 112
1
<stroke
        android:width="2dp"
        android:color="#808080" />

try it, it will work definitely

hexhog
  • 3
  • 3
jigar
  • 1,571
  • 6
  • 23
  • 46
0

Change the style to greenShape.getPaint().setStyle(Paint.Style.STROKE) and

greenShape.setShaderFactory(new ShapeDrawable.ShaderFactory() {
        @Override
        public Shader resize(int width, int height) {
            return new LinearGradient(0, 0, 0, 0, Color.WHITE, Color.WHITE, Shader.TileMode.REPEAT);
Patrick
  • 61
  • 6