Using a gradientDrawable with more than three colors set

不羁的心 提交于 2019-12-18 12:16:29

问题


According to what I've read, you can use a gradientDrawable and have three colors set for it, for example:

<gradient startColor="#00FF00" centerColor="#FFFF00" endColor="#FFFFFF"/>

But what if I want more than three colors, and not only that, I want to be able to set where to put each (in weight/percentage)?

Is it possible using the API or should I make my own customized drawable? If I need to make my own customized drawable, how should I do it?


回答1:


put this code in your onCreate() method:

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);

and use this drawable as a background.

You can add more than three colors in xml also by creating layers. But in XML it is quite complicated.




回答2:


It is not possible to do into a xml file, but you can apply +3 color gradient in yout java code with GradientDrawable class:

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);



回答3:


I think the below are possible solutions.

  • You can create multiple shapes with gradients and form a bigger shape.
  • You can create your own GradientDrawable by extending the GradientDrawable Class refer to the below doc.

  • Gradient Drawable Documentation



来源:https://stackoverflow.com/questions/14020530/using-a-gradientdrawable-with-more-than-three-colors-set

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