Rectangle shape with two solid colors

后端 未结 3 2071
北荒
北荒 2021-02-14 12:52

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

\"enter

3条回答
  •  礼貌的吻别
    2021-02-14 13:25

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

提交回复
热议问题