2012-12-24 26 views
13

据我读过,你可以使用一个gradientDrawable,自己也设定了三个颜色,例如:使用gradientDrawable有超过三种颜色设置

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

但是如果我想不止三种颜色,而且不仅如此,我希望能够设置每个位置(按重量/百分比)?

是否有可能使用API​​或我应该自己定制drawable?如果我需要制作自己的可定制绘图,我该怎么做?

+0

我认为你可以找到答案[这里](HTTP: //stackoverflow.com/questions/4381033/multi-gradient-shapes)。 – Androidz

回答

15

把这个代码在你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); 

并以此绘制作为背景。

通过创建图层,您还可以在xml中添加三种以上的颜色。但是在XML中它相当复杂。

+0

这看起来不错,但我该如何使用它?另外,是否有可能把它作为一个定制的可绘制的? –

+0

像如果你必须设置操作栏背景: getActionBar()。setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); getActionBar()。setBackgroundDrawable(paint); 或者如果你有一个按钮: //在你的xml文件中定义一个按钮,其中Id为按钮 Button button =(Button)findViewById(R.id.button); button.setBackgroundDrawable((Drawable)paint); – Bhaskar

+0

这看起来很酷。所以如果我想要一个定制的drawable,我需要做的就是扩展PaintDrawable,然后把你设置的代码放在它自己的地方? –

1

我认为以下是可能的解决方案。

  • 您可以使用渐变创建多个形状并形成更大的形状 形状。
  • 您可以通过扩展 GradientDrawable Class参考以下文档来创建自己的GradientDrawable。

  • Gradient Drawable Documentation

+0

你可以给我们看一下如何做第二个例子吗? –

2

这是不可能做成XML文件,但你可以在GradientDrawable类YOUT 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); 
+0

这也是一个很好的解决方案,而短。 –