Drawing a filled rectangle with a border in android Drawing a filled rectangle with a border in android android android

Drawing a filled rectangle with a border in android


Try paint.setStyle(Paint.Style.FILL) and paint.setStyle(Paint.Style.STROKE).

Paint paint = new Paint();Rect r = new Rect(10, 10, 200, 100);@Overridepublic void onDraw(Canvas canvas) {    // fill    paint.setStyle(Paint.Style.FILL);    paint.setColor(Color.MAGENTA);     canvas.drawRect(r, paint);    // border    paint.setStyle(Paint.Style.STROKE);    paint.setColor(Color.BLACK);    canvas.drawRect(r, paint);}


If you are drawing multiple views then you could also use two paints, one for the stroke and one for the fill. That way you don't have to keep resetting them.

enter image description here

Paint fillPaint = new Paint();Paint strokePaint = new Paint();RectF r = new RectF(30, 30, 1000, 500);void initPaints() {    // fill    fillPaint.setStyle(Paint.Style.FILL);    fillPaint.setColor(Color.YELLOW);    // stroke    strokePaint.setStyle(Paint.Style.STROKE);    strokePaint.setColor(Color.BLACK);    strokePaint.setStrokeWidth(10);}@Overrideprotected void onDraw(Canvas canvas) {    // First rectangle    canvas.drawRect(r, fillPaint);    // fill    canvas.drawRect(r, strokePaint);  // stroke    canvas.translate(0, 600);    // Second rectangle    int cornerRadius = 50;    canvas.drawRoundRect(r, cornerRadius, cornerRadius, fillPaint);    // fill    canvas.drawRoundRect(r, cornerRadius, cornerRadius, strokePaint);  // stroke}


You draw a rectangle with the color of the border and the size of the rectangle plus the border, you change the color of the paint and draw again the rectangle with the normal size.