Create a Shape dynamically

2019-04-26 12:42发布

问题:

I have a shape object defined in XML like below:

<shape android:shape="rectangle">
    <gradient
        android:startColor="#333"
        android:centerColor="#DDD"
        android:endColor="#333"/>
    <stroke android:width="1dp" android:color="#FF333333" />
</shape>

I want to create an equal object in my code. I created a GradientDrawable as below:

gradientDrawable1.setColors(new int[] { 0x333, 0xDDD, 0x333 });
gradientDrawable1.setOrientation(Orientation.TOP_BOTTOM);

But I don't know how to create a Stroke(?) and then assign both Stroke and GradientDrawable to Shape

Any idea?

回答1:

Example:

import android.graphics.drawable.GradientDrawable;

public class SomeDrawable extends GradientDrawable {

    public SomeDrawable(int pStartColor, int pCenterColor, int pEndColor, int pStrokeWidth, int pStrokeColor, float cornerRadius) {
        super(Orientation.BOTTOM_TOP,new int[]{pStartColor,pCenterColor,pEndColor});
        setStroke(pStrokeWidth,pStrokeColor);
        setShape(GradientDrawable.RECTANGLE);
        setCornerRadius(cornerRadius);
    }

}

Usage:

public class MyActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SomeDrawable vDrawable = new SomeDrawable(Color.BLACK,Color.GREEN,Color.LTGRAY,2,Color.RED,50);
        View vView = new View(this);
        vView.setBackgroundDrawable(vDrawable);
        setContentView(vView);
    }


}

Result:



回答2:

this should surely work, Try gradientDrawable1.setStroke(1, getResources().getColor(R.color.stroke));

so your code should be :

    GradientDrawable gradientDrawable1 = new GradientDrawable(Orientation.TOP_BOTTOM, new int[]{getResources().getColor(R.color.start),getResources().getColor(R.color.center),getResources().getColor(R.color.start)} );
    gradientDrawable1.setStroke(1, getResources().getColor(R.color.stroke));

where color stroke,start,center is defined inside colors.xml as:

 <color name="stroke">#FF333333</color>
 <color name="start">#333</color> 
 <color name="center">#ddd</color>


回答3:

if you want to make it in the code, first inspect what class instance is returned by res.getDrawable(resId) e.g by:

Drawable d = res.getDrawable(R.drawable.shape)
Log.d(TAG, "d: " + d)