and*_*per 15 android gradient colors android-drawable
根据我读过的内容,您可以使用gradientDrawable并为其设置三种颜色,例如:
<gradient startColor="#00FF00" centerColor="#FFFF00" endColor="#FFFFFF"/>
Run Code Online (Sandbox Code Playgroud)
但是,如果我想要超过三种颜色,不仅如此,我希望能够设置每个颜色的位置(重量/百分比)?
是否可以使用API或我应该制作自己的自定义drawable?如果我需要制作自己定制的可绘制的,我应该怎么做?
小智 22
将此代码放在onCreate()方法中:
ShapeDrawable.ShaderFactory shaderFactory = new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
LinearGradient linearGradient = new LinearGradient(0, 0, width, height,
new int[] {
0xFF1e5799,
0xFF207cca,
0xFF2989d8,
0xFF207cca }, //substitute the correct colors for these
new float[] {
0, 0.40f, 0.60f, 1 },
Shader.TileMode.REPEAT);
return linearGradient;
}
};
PaintDrawable paint = new PaintDrawable();
paint.setShape(new RectShape());
paint.setShaderFactory(shaderFactory);
Run Code Online (Sandbox Code Playgroud)
并使用此drawable作为背景.
您也可以通过创建图层在xml中添加三种以上的颜色.但是在XML中它非常复杂.
无法进入xml文件,但您可以使用GradientDrawable类在Java代码中应用+3颜色渐变:
GradientDrawable gradientDrawable = new GradientDrawable(
Orientation.TOP_BOTTOM,
new int[]{ContextCompat.getColor(this, R.color.color1),
ContextCompat.getColor(this, R.color.color2),
ContextCompat.getColor(this, R.color.color3),
ContextCompat.getColor(this, R.color.color4)});
findViewById(R.id.background).setBackground(gradientDrawable);
Run Code Online (Sandbox Code Playgroud)