Is there any way in Android to draw a filled rectangle with say a black border. My problem is that the canvas.draw() takes one paint object, and to my knowledge the paint object can't have a different color for the fill and the stroke. Is there a way around this?
Asked
Active
Viewed 9.9k times
62
-
1You're right. Just draw the filled rect first and then the stroke around the outside. – Gene Nov 24 '12 at 21:31
3 Answers
157
Try paint.setStyle(Paint.Style.FILL) and paint.setStyle(Paint.Style.STROKE).
Paint paint = new Paint();
Rect r = new Rect(10, 10, 200, 100);
@Override
public 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);
}

wannik
- 12,212
- 11
- 46
- 58
-
Is there also a way to do this for canvas.drawRoundRect()? Because in my case, the border has now rounded corners, even though I draw it also with canvas.drawRoundRect(). – Chris Nov 06 '13 at 16:05
-
6I know that the answer is old, but I want to share this little line paint.setPathEffect(new CornerPathEffect(radius)); to answering the Chris' question. I just answer because can be somebody need help. – Crash Jan 25 '16 at 20:40
-
@Crash it's better to use `drawRoundRect` for dynamic radius (based on rect size) – user924 Oct 08 '18 at 11:21
50
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.
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);
}
@Override
protected 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
}

Suragch
- 484,302
- 314
- 1,365
- 1,393
1
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.

yDelouis
- 2,094
- 17
- 18
-
17Note that this results in a drawing the same area almost twice – Radu Simionescu Nov 06 '14 at 09:09