安卓线性渐变XML

36

我在XML中使用LinearGradient定义时遇到了小问题。我想要使用接受颜色数组和位置数组的构造函数。

就是这个构造函数:

    LinearGradient(float x0, float y0, float x1, float y1, 
int[] colors, float[] positions, Shader.TileMode tile)

我该如何将数组传递到XML中?这是一个带有渐变定义的XML示例,但它很简单。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:startColor="#474946"
        android:endColor="#181818"
        android:angle="270"/>
    <corners android:radius="5dp" />
</shape>
4个回答

70

很遗憾,使用XML定义GradientDrawable时只允许使用三种以上的颜色。

请查看官方参考文档:http://developer.android.com/reference/android/graphics/drawable/GradientDrawable.html.

示例:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:startColor="#474946"
        android:centerColor="#ff0000"
        android:endColor="#181818"
        android:angle="270"/>
    <corners android:radius="5dp" />
</shape>

因此,在您的情况下,您将使用android:CenterColor添加一种颜色。 但是对于超过三种颜色的情况,您甚至需要使用Java来完成。


20

@Juriy, @ErickPetru:

我支持ErickPetru的回答。不过我想提醒一下,还有一个特性可用:不仅可以指定中心颜色,还可以指定中心偏移量,这样可以提供更多灵活性,有时也有助于避免必须进行Java编码。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <corners
        android:radius="5dp" />
    <gradient
        android:type="linear"
        android:startColor="#FF000000"
        android:centerColor="#FF303030"
        android:endColor="#FFE0E0E0"
        android:centerX="0.2"
        android:centerY="0.3"
        android:angle="270" />
</shape>

7

0

如果你正在Java上创建渐变,你有一个选项。

LinearGradient lg = new LinearGradient(0, 0, width, height,
            new int[]{Color.GREEN, Color.GREEN, Color.WHITE, Color.WHITE},
            new float[]{0,0.5f,.55f,1}, Shader.TileMode.REPEAT);

将此设置为您视图的背景。


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