【问题标题】:Android LinearGradient XMLAndroid 线性渐变 XML
【发布时间】:2011-03-14 15:26:20
【问题描述】:

我遇到了 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>

【问题讨论】:

    标签: android xml


    【解决方案1】:

    很遗憾,使用 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 来完成。

    【讨论】:

      【解决方案2】:

      @Juriy,@ErickPetru:

      +1 表示 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>
      

      【讨论】:

        【解决方案3】:

        您需要在 Java 代码中执行此操作。 API Demos 中的ShapeDrawable1.java 有一个示例。

        Shape Drawable 详细介绍了 xml 中可用的内容。

        【讨论】:

          【解决方案4】:

          如果您在 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);
          

          将此设置为视图的背景。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-06-30
            • 2011-04-29
            • 1970-01-01
            • 2016-01-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多