具有两个纯色的矩形形状 [英] Rectangle shape with two solid colors
问题描述
我想创建一个具有两个纯色(水平)的矩形形状,以实现以下目的:
I'd like to create a rectangle shape with two solid colors (horizontally) to achieve something like this:
我听说过layer-list
,尽管我可以用它包含两个具有不同颜色的矩形,但是看来它只能垂直放置形状.
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.
有没有一种方法可以使用lalyer-list来实现?还是应该使用完全不同的方法?我想通过在运行时更改形状颜色的功能使其简单.
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.
谢谢.
推荐答案
您可以为此创建自定义可绘制对象.只需扩展Drawable类.
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;
}
}
这篇关于具有两个纯色的矩形形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!