以编程方式创建Android Gradient Drawable

12

我有一个在xml中定义的渐变形状,我将它作为背景使用,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:bottom="4dp">
      <shape>
         <gradient
            android:startColor="@color/blue"
            android:endColor="@color/dark_blue"
            android:angle="270" />
      </shape>
   </item>
   <item android:top="98dp">
      <shape>
         <gradient
            android:startColor="@color/black"
            android:endColor="@color/transparent_black"
            android:angle="270" />
      </shape>
   </item>
</layer-list>

我需要以程序方式实现这个功能。我已经尝试使用GradientDrawable,如下所示(此方法在自定义视图上实现):

int[] colors1 = {getResources().getColor(R.color.black), getResources().getColor(R.color.trasparent_black)};

GradientDrawable shadow = new GradientDrawable(Orientation.TOP_BOTTOM, colors1);
shadow.setBounds(0,98, 0, 0);
        
int[] colors = new int[2];
colors[0] = getResources().getColor(R.color.blue);
colors[1] = getResources().getColor(R.color.dark_blue);

GradientDrawable backColor = new GradientDrawable(Orientation.TOP_BOTTOM, colors);

backColor.setBounds(0, 0,0, 4);

//finally create a layer list and set them as background.    
Drawable[] layers = new Drawable[2];
layers[0] = backColor;
layers[1] = shadow;
      
LayerDrawable layerList = new LayerDrawable(layers);
setBackgroundDrawable(layerList);
        
问题在于,似乎设置边界是无用的,或者与 (android:top, android:bottom xml参数) 的工作方式不同。结果背景是每个图层从上到下依次绘制出来的,一个在另一个上面。
我想生成类似这样的东西:IMG
1个回答

9

找到了答案!可能是重复的问题多重渐变形状

替换为:

backColor.setBounds(0, 0,0, 4);
shadow.setBounds(0,98, 0, 0);

for

layerList.setLayerInset(0, 0, 0, 0, 4);
layerList.setLayerInset(1, 0, 98, 0, 0);     

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