-->

Why doesn't this argument of the LinearGradien

2019-08-15 03:25发布

问题:

I want to set a custom drawable with a linear gradient as the background drawable of the bar in my SeekBar. I am creating the LinearGradient in the second statement in the following snippet, and doing it like so:

// 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);

The problem here is that, according to the specification, the 6th parameter is defined as

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.

I wanted both the red and blue colors to be distributed evenly, i.e. half the shape should appear redish and half should appear bluish (like the following image).

So I tried null, new float[] {0, 0.5f}, and new float[] {0, 1} as values of the 6th argument. I got the following three results respectively.

  1. For null:

  2. For new float[] {0, 0.5f}:

  3. For new float[] {0, 1}:

Show where am I going wrong? How should I fix this?

回答1:

use

ShapeDrawable#setShaderFactory(ShapeDrawable.ShaderFactory factory)

the factory has a method Shader resize(int width, int height) which is called every time your drawable bounds change and this is a place where you should return your LinearGradient shader based on width / height parameters

as you will see you can now just pass null positions and colors will be distributed evenly