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

1

3

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).

enter image description here

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: enter image description here

  2. For new float[] {0, 0.5f}: enter image description here

  3. For new float[] {0, 1}: enter image description here

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

Viviyan answered 13/3, 2016 at 19:3 Comment(6)
see ShapeDrawable.ShaderFactoryPachydermatous
@Pachydermatous Thank you I am gonna implement it.Viviyan
@Pachydermatous Thank you so very much. This works. Can you post it as an answer so that I can mark it as accepted.Viviyan
note that when using ShaderFactory you dont need to call shapeDrawable.getPaint().setShader(linearGradientShader); and shapeDrawable.setBounds(10, 10, 300, 30);Pachydermatous
Oh yeah, I didn't do that. Thank you so very much.Viviyan
your welcome, no problemPachydermatous
P
2

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

Pachydermatous answered 14/3, 2016 at 8:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.