问题描述
我想将具有线性渐变的自定义可绘制对象设置为我的SeekBar
中条的背景可绘制对象.我在以下代码段的第二条语句中创建LinearGradient,并这样做:
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);
这里的问题是,根据 规范 ,第6个参数定义为
The problem here is that, according to the specification, the 6th parameter is defined as
我希望红色和蓝色都均匀分布,即一半的形状应偏红色,一半的颜色应偏蓝色(如下图所示).
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).
所以我尝试了null
,new float[] {0, 0.5f}
和new float[] {0, 1}
作为第6个参数的值.我分别得到以下三个结果.
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.
-
对于
null
:
对于new float[] {0, 0.5f}
:
对于new float[] {0, 1}
:
显示我要去哪里错了?我该如何解决?
推荐答案
使用
工厂有一个方法Shader resize(int width, int height)
,每次您的可绘制范围更改时都会调用该方法,在这里您应该根据width
/height
参数返回您的LinearGradient
着色器
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
您将看到,现在只需传递null positions
,颜色就会均匀分布
as you will see you can now just pass null positions
and colors will be distributed evenly
这篇关于为什么LinearGradient构造函数的此参数似乎不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!