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

天大地大妈咪最大 提交于 2019-12-11 00:39:44

问题


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



来源:https://stackoverflow.com/questions/35974463/why-doesnt-this-argument-of-the-lineargradient-constructor-seem-to-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!