为什么 LinearGradient 构造函数的这个参数似乎不起作用?

Why doesn't this argument of the LinearGradient constructor seem to work?

我想在 SeekBar 中设置一个具有线性渐变的自定义可绘制对象作为栏的背景可绘制对象。我在以下代码片段的第二条语句中创建了 LinearGradient,并且这样做:

// Creating the drawable:
ShapeDrawable shapeDrawable = new ShapeDrawable(new RectShape());
Shader linearGradientShader = new LinearGradient(0, 0, 300, 20, new int[] { Color.RED, Color.BLUE },
new float[] { 0, 1 }, Shader.TileMode.CLAMP);
shapeDrawable.getPaint().setShader(linearGradientShader);
shapeDrawable.setBounds(10, 10, 300, 30);

seekBar.setProgressDrawable(shapeDrawable);

这里的问题是,根据specification,第6个参数定义为

May be null. The relative positions [0..1] of each corresponding color in the colors array. If this is null, the the colors are distributed evenly along the gradient line.

我希望红色和蓝色的颜色均匀分布,即一半的形状应该呈现红色,一半应该呈现蓝色(如下图)。

所以我尝试将 nullnew float[] {0, 0.5f}new float[] {0, 1} 作为第 6 个参数的值。我分别得到了以下三个结果

  1. 对于null

  2. 对于new float[] {0, 0.5f}

  3. 对于new float[] {0, 1}

显示我哪里出错了?我该如何解决?

使用

ShapeDrawable#setShaderFactory(ShapeDrawable.ShaderFactory factory)

工厂有一个方法 Shader resize(int width, int height) 每次你的可绘制边界改变时都会调用它,这是你应该 return 你的 LinearGradient 着色器基于 width / height 参数

如您所见,您现在只需传递 null positions,颜色就会均匀分布