我创建了一个带有自定义LinearGradient
可绘制对象的搜索栏。但是,我希望能够更改每种颜色的渐变比率,这里我使用3种颜色,如果positions
is ,它们将平均分布null
。我想要的,其实是提供宽度或比于每种颜色,例如红色的变化率,并将其设置只形成0%至10%的seekBar
width
。
在这里,我想将0%设置为10%的红色,10%设置为80%的黄色,并将80%设置为100%的红色,并且能够动态更改每种颜色的宽度值。
这有可能吗?如果是,有人可以指导我如何做吗?
我的密码
private ShapeDrawable getSeekBarGradientDrawable(int mRectWidth, int mRectHeight) {
int[] colors = new int[] { Color.RED, Color.YELLOW, getResources().getColor(R.color.primaryButton, null)};
DisplayMetrics displayMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int width = displayMetrics.widthPixels - (int) getResources().getDimension(R.dimen.margin_padding_size_medium);
Shader shader = new LinearGradient(
0,
0,
width,
mRectHeight,
colors, new float[] {0.1f,0.7f,0.2f},
Shader.TileMode.CLAMP);
ShapeDrawable shape = new ShapeDrawable(new RectShape());
shape.getPaint().setShader(shader);
return shape;
}
图像可以从当前设置中看到,其不像我描述的那样。
此答案适用于将LinearGradient用作着色器。
通过如下设置数组,将LinearGradient颜色更改为从一种颜色过渡到同一颜色colors
:
int[] colors = new int[]{Color.RED, Color.RED, Color.YELLOW, Color.YELLOW, Color.GREEN, Color.GREEN};
更改LinearGradient以定义颜色区域,如下所示:请参见带有位置的LinearGradient
Shader shader = new LinearGradient(
0,
0,
width,
mRectHeight,
colors, new float[]{0f, 0.1f, 0.1f, 0.8f, 0.8f, 1.0f},
Shader.TileMode.CLAMP);
这将迫使着色器在一个区域上从一种颜色过渡到同一颜色,从而创建纯色。
以上将提供从一种颜色到另一种颜色的即时转换。如果您想要一个狭窄的过渡(比LinearGradient的默认过渡窄),则可以如下操作color和position数组。接下来,我们将过渡从红色更改为黄色。
int[] colors = new int[]{Color.RED, Color.RED, Color.YELLOW, Color.YELLOW, Color.YELLOW, Color.GREEN, Color.GREEN};
Shader shader = new LinearGradient(
0,
0,
width,
mRectHeight,
colors, new float[]{0f, 0.1f, 0.15f, 0.15f, 0.8f, 0.8f, 1.0f},
Shader.TileMode.CLAMP);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句