Android的渐变绘制对象编程 [英] Android Gradient drawable programmatically

查看:103
本文介绍了Android的渐变绘制对象编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在XML定义的梯度绘制,我用它作为背景,像这样的:

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

<?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如下(此方法在自定义视图实现):

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

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

现在的问题是,它似乎在设定界限是无用的或不工作的方式相同(安卓顶部,机器人:底部XML参数)。则产生的背景是绘从上到下各层,一个在另一个之上。

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.

我想产生这样的:

I want to generate something like this:

推荐答案

找到了答案!可能的重复多梯度图形

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

替换:

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

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

这篇关于Android的渐变绘制对象编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆