以编程方式绘制 Android Gradient

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12427025/
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-08-20 10:38:05  来源:igfitidea点击:

Android Gradient drawable programmatically

androidbackgrounddrawable

提问by marbarfa

I have a gradient drawable defined in xml that I use it as a background, like this:

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

I need to implement this programmatically. I have tried to use a GradientDrawable as follows (this method is implemented on a custom view):

我需要以编程方式实现这一点。我尝试使用 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);

The problem is that it seems that setting the bounds is useless or doesn't work the same way as (android:top, android:bottom xml parameters). The resulting background is each layer painted from top to bottom, one above the other.

问题是,设置边界似乎没有用或与 (android:top, android:bottom xml 参数) 的工作方式不同。生成的背景是从上到下绘制的每一层,一层在另一层之上。

I want to generate something like this: IMG

我想生成这样的东西: IMG

采纳答案by marbarfa

Found the answer!. Possible duplicate Multi-gradient shapes.

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

Replaced:

替换:

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