【发布时间】:2017-07-20 21:07:53
【问题描述】:
我需要创建一个具有 5 种不同颜色的线性渐变。 我尝试了以下方法:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<layer-list>
<item>
<shape>
<gradient
android:startColor="@color/diagramBlueColor"
android:endColor="@color/diagramGreenColor"
android:type="linear"
android:angle="0" />
</shape>
</item>
<item>
<shape>
<gradient
android:startColor="@color/diagramGreenColor"
android:endColor="@color/diagramYellowColor"
android:type="linear"
android:angle="0" />
</shape>
</item>
<item>
<shape>
<gradient
android:startColor="@color/diagramYellowColor"
android:endColor="@color/diagramOrangeColor"
android:type="linear"
android:angle="0" />
</shape>
</item>
<item>
<shape>
<gradient
android:startColor="@color/diagramOrangeColor"
android:endColor="@color/diagramRedColor"
android:type="linear"
android:angle="0" />
</shape>
</item>
</layer-list>
</item>
</selector>
但是每个形状都覆盖了之前的形状。我需要使用 xml 创建渐变。我该怎么做?
如果纯 xml 无法实现,那么我该如何在 java 代码中实现呢? 我试过这个:
/**
*
* @return
*/
public static PaintDrawable getColorScala() {
ShapeDrawable.ShaderFactory shaderFactory = new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
LinearGradient linearGradient = new LinearGradient(0, 0, width, height,
new int[] {
0xFF1e5799,
0xFF207cca,
0xFF2989d8,
0xFF207cca }, //substitute the correct colors for these
new float[] {
0, 0.40f, 0.60f, 1 },
Shader.TileMode.REPEAT);
return linearGradient;
}
};
PaintDrawable paint = new PaintDrawable();
paint.setShape(new RectShape());
paint.setShaderFactory(shaderFactory);
return paint;
}
但是当我设置视图的背景时:
view.setBackground(Colors.getColorScala());
我视图的背景是白色的。我希望它看起来像这样:
【问题讨论】:
-
纯xml无法做到,需要java代码做到