2013-07-13 44 views
8

長方形我想創建兩個純色(水平)的矩形形狀來實現這樣的事情:兩種純色

enter image description here

我聽說layer-list,我以爲我可以使用它包含兩個不同顏色的矩形,但它似乎只是垂直放置形狀。

有沒有辦法使用lalyer-list來實現這個目標,還是應該使用完全不同的東西?我想保持它簡單,能夠在運行時更改形狀顏色。

謝謝。

+0

看到九個補丁drawables – pskink

+0

@nathan看到我的答案! –

回答

6

您可以爲此創建自定義繪圖。只需擴展Drawable類。

下面是一個示例代碼,它可以繪製出您想要的矩形,您可以提供任意數量的顏色。

public class ColorBarDrawable extends Drawable { 

    private int[] themeColors; 

    public ColorBarDrawable(int[] themeColors) { 
     this.themeColors = themeColors; 
    } 

    @Override 
    public void draw(Canvas canvas) { 

     // get drawable dimensions 
     Rect bounds = getBounds(); 

     int width = bounds.right - bounds.left; 
     int height = bounds.bottom - bounds.top; 

     // draw background gradient 
     Paint backgroundPaint = new Paint(); 
     int barWidth = width/themeColors.length; 
     int barWidthRemainder = width % themeColors.length; 
     for (int i = 0; i < themeColors.length; i++) { 
      backgroundPaint.setColor(themeColors[i]); 
      canvas.drawRect(i * barWidth, 0, (i + 1) * barWidth, height, backgroundPaint); 
     } 

     // draw remainder, if exists 
     if (barWidthRemainder > 0) { 
      canvas.drawRect(themeColors.length * barWidth, 0, themeColors.length * barWidth + barWidthRemainder, height, backgroundPaint); 
     } 

    } 

    @Override 
    public void setAlpha(int alpha) { 
    } 

    @Override 
    public void setColorFilter(ColorFilter cf) { 

    } 

    @Override 
    public int getOpacity() { 
     return PixelFormat.OPAQUE; 
    } 

} 
+0

謝謝。它的工作:) – nathan

+0

我們如何設置這個解決方案圓角? –

16

這必將繪製形狀按您的要求:

,因爲你需要調整的<item>大小!

<?xml version="1.0" encoding="utf-8"?> 
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" > 

    <item 
     android:left="50dip"> 
     <shape 
      xmlns:android="http://schemas.android.com/apk/res/android" 
      android:shape="rectangle" > 
      <solid android:color="#0000FF" /> 
     </shape> 
    </item> 
    <item android:right="50dip"> 
     <shape 
      xmlns:android="http://schemas.android.com/apk/res/android" 
      android:shape="rectangle" > 
      <solid android:color="#ff0000" /> 
     </shape> 
    </item> 

</layer-list> 
+2

不錯的一個..是否可以添加四捨五入的邊框只有特定的一面? – Bora

+2

我們可以讓左側match_parent? – bharv14

+1

偉大的解決方案謝謝! –

0

這會給你兩種顏色的一半和一半垂直。將此代碼放在drawable資源中。

<item 
    android:top="320dip"> 
    <shape 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     android:shape="rectangle" > 
     <solid android:color="@color/red" /> 
    </shape> 
</item> 
<item android:bottom="320dip"> 
    <shape 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     android:shape="rectangle" > 
     <solid android:color="@color/yellow" /> 
    </shape> 
</item>