Rounded corners drawable via code

1.7k Views Asked by At

I have a drawable that will change colors sometimes, but it must ALWAYS have rounded corners. It's for a UI library, so I can't know what colors will it have. XML is not an option, I have to achieve this with pure java.

Is there a way to achieve this programatically WITHOUT using XML?

3

There are 3 best solutions below

2
On BEST ANSWER

Create a custom Drawable (i.e. extend Drawable) and in its onDraw use Canvas.drawRoundRect(RectF rect, float rx, float ry, Paint paint), setting the Paint to the desired colour.

0
On

Based on the answer from @nmw, here's some code that works for this:

public class RRDrawable extends Drawable {
    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

    public RRDrawable(int color) {
        paint.setColor(color);
        paint.setStyle(Paint.Style.FILL);
    }

    @Override
    public void draw(Canvas canvas) {
        int radius = 10; // note this is actual pixels
        canvas.drawRoundRect(new RectF(0,0,canvas.getWidth(), canvas.getHeight()), radius, radius,  paint);
    }

    @Override
    public void setAlpha(int i) {
        //.. not supported
    }

    @Override
    public void setColorFilter(ColorFilter colorFilter) {
        //.. not supported
    }

    @Override
    public int getOpacity() {
        return 1;
    }
}

EDIT: added anti-aliasing to the edges.

(source)

0
On

If you draw the drawable by yourself, you could set a clip path with Canvas.clipPath. The path would consist of one or more rectangles and some circles, which clip the rounded corners. You probably have to play around with the arrangement of the path components until you get the desired output.