2012-12-24 25 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

這也是一個很好的解決方案,而短。 –