如何使用Android GradientDrawable

Jan*_*usz 28 android android-layout

我尝试使用GradientDrawable将渐变设置为某些背景和按钮.可悲的是,文档不是很详细.

配置渐变的主要属性是什么?我理解start和endcolor,但其他一些属性可能需要一些解释.

目前我使用图像作为按钮的背景,但是用XML定义的drawable会更好.

我试着看起来像这样(它是一个非常轻的渐变):alt text http://janusz.de/~janusz/RedButton.png

Pra*_*een 41

使用此xml作为imageview的背景.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient android:angle="90" android:startColor="#7c0000" android:endColor="#A71C1C"/>
</shape>
Run Code Online (Sandbox Code Playgroud)

而已.

  • 它也适合我,但我想了解它是如何工作的...一些代码片段不能帮助我理解这个问题 (3认同)

Dan*_*son 39

我将给出与Praveen相同的答案,但也将尝试解释设置.

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient 
       android:type="linear" 
       android:angle="-90" 
       android:startColor="#7c0000" 
       android:endColor="#A71C1C" />
</shape>
Run Code Online (Sandbox Code Playgroud)

机器人:类型

有三种类型的渐变,默认和此问题的一种是"线性".另外2个是"径向"和"扫描".

机器人:角

逆时针旋转渐变,其中0为| 开始颜色 - >结束颜色| (水平方向).

机器人:startColor

颜色渐变开始,开始由旋转定义.

机器人:ENDCOLOR

颜色渐变结束,结束由旋转定义.

机器人:centerColor

如果需要,在开始颜色和结束颜色之间也可以有颜色.

  • 好.只是为了澄清,如果角度为270(或-90),则起始颜色位于顶部,而最终颜色位于底部. (6认同)

Sur*_*gch 7

在此处输入图片说明

代码

我最初发现这个问题是因为我想用代码来做。以下是如何以编程方式执行此操作。

int startColor = 0xfff6ee19; // yellow
int endColor = 0xff115ede;   // blue
GradientDrawable gradientDrawable = new GradientDrawable(
        GradientDrawable.Orientation.LEFT_RIGHT,
        new int[] {startColor, endColor});

View myView = findViewById(R.id.my_view);
myView.setBackgroundDrawable(gradientDrawable);
Run Code Online (Sandbox Code Playgroud)

顶部图像中的不同方向可以通过更改Orientation构造函数中的来实现。

XML

正如已经回答的那样,这就是您在 xml 中的处理方式。

my_gradient_drawable.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:type="linear"
        android:angle="0"
        android:startColor="#f6ee19"
        android:endColor="#115ede" />
</shape>
Run Code Online (Sandbox Code Playgroud)

您将其设置为某个视图的背景。例如:

<View
    android:layout_width="200dp"
    android:layout_height="100dp"
    android:background="@drawable/my_gradient_drawable"/>
Run Code Online (Sandbox Code Playgroud)

也可以看看