Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rectangle shape with two solid colors

I'd like to create a rectangle shape with two solid colors (horizontally) to achieve something like this:

enter image description here

I heard about layer-list, i though i could use it to contains two rectangle with a different color but it seems that it only lays shapes vertically.

Is there a way to achieve this using lalyer-list or should i use something totally different? I'd like to keep it simple with ability to change the shape colors at runtime.

Thanks.

like image 512
nathan Avatar asked Jul 13 '13 13:07

nathan


2 Answers

You can create custom drawable for this. Just extend Drawable class.

Here is a sample code which draws a rectangle like you wanted, you can provide any number of colors.

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

}
like image 52
Chiral Code Avatar answered Nov 20 '22 13:11

Chiral Code


this will surely draw the shape as per your Requirement :

Adjust size of <item> as you need !

<?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>
like image 26
Tarsem Singh Avatar answered Nov 20 '22 12:11

Tarsem Singh