使用具有三种以上颜色的gradientDrawable

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中它非常复杂.

  • 这个答案很有效.对于从上到下的渐变,将渐变的创建替换为以下内容:"LinearGradient(0,0,0,height,..."(因此将第二个渐变点替换为0 |高度而不是width | height) (2认同)

Pel*_*nes 7

无法进入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)