Create a Shape dynamically

2019-04-26 12:00发布

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?

3条回答
对你真心纯属浪费
2楼-- · 2019-04-26 12:32

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:

Drawable result image

查看更多
虎瘦雄心在
3楼-- · 2019-04-26 12:32

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)
查看更多
再贱就再见
4楼-- · 2019-04-26 12:37

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">#ffffd</color>
查看更多
登录 后发表回答