以编程方式更改可绘制的圆角半径

时间:2012-07-12 08:27:16

标签: java android xml drawable shape

我在xml中定义了这个形状:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#FFFF0000"
        android:endColor="#80FF00FF"
        android:angle="45"/>
    <padding android:left="7dp" 
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <corners
        android:bottomLeftRadius="5dp"    ##this need change
        android:bottomRightRadius="5dp"   ##this need change
        android:topLeftRadius="5dp"       ##this need change
        android:topRightRadius="5dp" />   ##this need change
</shape>

我正在创建以下对象:

Drawable shape = getResource().getDrawable(R.drawable.myshape);

我需要修改它的半径(或者用另一个角半径创建一个半径)。

如何更改半径?如何以编程方式创建形状?

1 个答案:

答案 0 :(得分:21)

我解决了我的问题。解决方案在这里:

private Drawable getShape(){
    GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TL_BR, new int[] { startColor,
            centerColor, endColor});
    gradientDrawable.setGradientType(GradientDrawable.LINEAR_GRADIENT);
    gradientDrawable.setCornerRadii(getRandomFloatArray());
    gradientDrawable.setGradientCenter(0.0f, 0.45f);

    return gradientDrawable;
}

private float [] getRandomFloatArray(){
    Random rnd = new Random();
    float[] floats = new float[8];
    for (int i =0; i < floats.length; i++){
        floats[i] = rnd.nextInt(45);
    }
    return floats;
}