以编程方式创建径向渐变

17

我正在尝试通过编程复制以下渐变效果。

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient 
        android:startColor="@color/startcolor" 
        android:centerColor="#343434"
        android:endColor="#00000000"
        android:type="radial"
        android:gradientRadius="140"
        android:centerY="45%"
     />
    <corners android:radius="0dp" />
</shape>

如何以编程方式设置参数?谢谢

        android:centerY="45%"
1个回答

34

http://developer.android.com/reference/android/graphics/drawable/GradientDrawable.html

如果要设置特定的参数(我假设您要设置 centerX 值,因为您没有指定):

yourGradientDrawable.setGradientCenter(1.0f,  0.45f);

所以要通过编程方式创建上述渐变(除了不同的颜色):

GradientDrawable g = new GradientDrawable(Orientation.TL_BR, new int[] { getResources().getColor(R.color.startcolor), Color.rgb(255, 0, 0), Color.BLUE });
g.setGradientType(GradientDrawable.RADIAL_GRADIENT);
g.setGradientRadius(140.0f);
g.setGradientCenter(0.0f, 0.45f);

注意:径向渐变忽略方向,但是构造函数需要指定颜色。


5
这对我不起作用,没有径向渐变,只有纯白色背景。 - Poutrathor
1
如果您想使用默认中心值,则无需调用setGradientCenter - Felipe Conde

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