java 以编程方式更改drawable的圆角半径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11447835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:09:47  来源:igfitidea点击:

change corner radius of drawable programmatically

javaandroidxmldrawableshape

提问by Vetalll

I have this shape defined in an xml:

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

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?

我怎样才能改变半径?如何以编程方式创建形状?

回答by Vetalll

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