Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change corner radius of drawable programmatically

I have this shape defined in an 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>

I am creating the following object:

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

and I need to modify its radius (or create one with another corner radius).

How can I change the radius? How can I create the shape programmatically?

like image 644
Vetalll Avatar asked Jul 12 '12 08:07

Vetalll


1 Answers

I solved my problem. The solution is here:

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;
}
like image 148
Vetalll Avatar answered Oct 02 '22 03:10

Vetalll