JustMe
JustMe

Reputation: 10113

How to add a stroke to ShapeDrawable

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

Upvotes: 7

Views: 12231

Answers (4)

Sree Aurovindh
Sree Aurovindh

Reputation: 705

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!)

Upvotes: 14

Patrick
Patrick

Reputation: 61

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);

Upvotes: 0

jigar
jigar

Reputation: 1591

<stroke
        android:width="2dp"
        android:color="#808080" />

try it, it will work definitely

Upvotes: 1

CaseyB
CaseyB

Reputation: 25058

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?

Upvotes: 2

Related Questions