矩形形状带有两种实心颜色

11
我想创建一个带有两种实心颜色(横向)的矩形形状,实现类似于这样的效果: enter image description here 我听说过layer-list,我认为可以用它来包含具有不同颜色的两个矩形,但它似乎只能垂直放置形状。
是否有办法使用layer-list实现此目的,还是应该完全使用其他方法? 我希望保持简单,并能够在运行时更改形状颜色。
谢谢。

查看Nine Patch Drawables - pskink
3个回答

28

这肯定会按照您的要求绘制形状

根据需要调整<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
有没有办法将那些左/右值设置为比例而不是硬编码它们?希望能够重复使用可变尺寸的drawable。 - Wes Winn

10

您可以创建自定义的drawable。只需扩展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;
    }

}

1

这将为您提供两种垂直分割的颜色。将此代码放入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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接