【问题标题】:Why doesn't this argument of the LinearGradient constructor seem to work?为什么 LinearGradient 构造函数的这个参数似乎不起作用?
【发布时间】:2016-06-28 17:16:09
【问题描述】:

我想在我的SeekBar 中设置一个具有线性渐变的自定义drawable 作为条形的背景drawable。我在以下 sn-p 的第二个语句中创建 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个参数定义为

可能为空。颜色数组中每个对应颜色的相对位置 [0..1]。如果为 null,则颜色沿渐变线均匀分布。

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

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

  1. 对于null

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

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

显示我哪里出错了?我应该如何解决这个问题?

【问题讨论】:

  • ShapeDrawable.ShaderFactory
  • @pskink 谢谢你我要去实现它。
  • @pskink 非常感谢。这行得通。您能否将其发布为答案,以便我将其标记为已接受。
  • 请注意,使用ShaderFactory时不需要调用shapeDrawable.getPaint().setShader(linearGradientShader);shapeDrawable.setBounds(10, 10, 300, 30);
  • 哦,是的,我没有那样做。非常感谢。

标签: android android-drawable linear-gradients android-shapedrawable


【解决方案1】:

使用

ShapeDrawable#setShaderFactory(ShapeDrawable.ShaderFactory 工厂)

工厂有一个方法Shader resize(int width, int height),每次你的可绘制边界发生变化时都会调用它,这是你应该根据width/height参数返回LinearGradient着色器的地方

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

【讨论】:

    猜你喜欢
    • 2022-01-04
    • 2016-08-15
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    • 2022-07-29
    • 1970-01-01
    • 2012-12-27
    相关资源
    最近更新 更多