【问题标题】:How to use Android GradientDrawable如何使用 Android GradientDrawable
【发布时间】:2010-04-19 09:11:16
【问题描述】:

我尝试使用 GradientDrawable 为某些背景和按钮设置渐变。 遗憾的是documentation 不是很详细。

配置渐变的主要属性有哪些?我了解 start 和 endcolor 但其他一些属性可能需要一些解释。

目前我使用图像作为按钮的背景,但在 XML 中定义的可绘制对象会更好。

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

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    使用这个 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>
    

    就是这样。

    【讨论】:

    • 在您提到的文档中设置 xml 属性。第一个 android:angle
    • ... 文档中的问题是它没有显示属性角度在做什么。你的回答产生了一个形状,但我仍然不知道 gradientDrawable 是如何工作的。
    • 它适用于我。我不知道你的问题。如果我有任何想法,请告诉你。
    • 它也适用于我,但我想了解它是如何工作的......一些代码 sn-ps 不能帮助我理解问题
    • 我相信你可以把这个形状想象成一个盒子,盒子的一端是开始颜色,另一端是结束颜色。角度旋转该框的角度。它需要玩,但我相信角度 0 将是 |开始颜色 --> 结束颜色 | (水平)。角度 90 可能会顺时针旋转框,将起始颜色置于结束颜色之上。
    【解决方案2】:

    我将给出与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>
    

    机器人:类型

    有 3 种类型的渐变,默认的,本题的一种是“线性”。另外两个是“径向”和“扫掠”。

    机器人:角度

    梯度逆时针旋转,其中0为|开始颜色 --> 结束颜色 | (水平)。

    android:startColor

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

    android:endColor

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

    android:centerColor

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

    【讨论】:

    • 好。澄清一下,如果角度为 270(或 -90),则起始颜色位于顶部,而结束颜色位于底部。
    • @Dandre Allison 嘿,我们可以在运行时更改 xml 渐变值
    【解决方案3】:

    代码

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

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

    可以通过改变构造函数中的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>
    

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

    <View
        android:layout_width="200dp"
        android:layout_height="100dp"
        android:background="@drawable/my_gradient_drawable"/>
    

    另见

    【讨论】:

      猜你喜欢
      • 2014-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多