动态创建形状

7

我有一个在XML中定义的形状对象,如下所示:

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

我想在我的代码中创建一个相等的对象。 我已经创建了一个如下的 GradientDrawable

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

但是我不知道如何创建一个Stroke(?),然后将Stroke和GradientDrawable都分配给Shape

有什么想法吗?

3个回答

8

例子:

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

}

使用方法:

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


}

结果:

可绘制结果图像


0

这应该肯定会成功尝试一下gradientDrawable1.setStroke(1, getResources().getColor(R.color.stroke));

所以你的代码应该是:

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

color stroke、start、centercolors.xml 中被定义为:

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

-5
如果你想在代码中实现它,首先要检查res.getDrawable(resId)返回的类实例是什么,例如:
Drawable d = res.getDrawable(R.drawable.shape)
Log.d(TAG, "d: " + d)

我不想从资源中获取对象。我想在Java代码中动态创建它。 - Ali Behzadian Nejad
你按照我写的做了吗?输出结果是什么? - pskink

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接