How to add round corner to canvas drawrect in Android?

user478489 picture user478489 · Oct 24, 2015 · Viewed 8.9k times · Source

I am creating a rectangle in @Override method of ReplacementSpan. How to add RoundCorner and padding to it?

Code:

@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
    RectF rect = new RectF(x, top, x + measureText(paint, text, start, end), bottom);
    paint.setColor(mBackgroundColor);
    canvas.drawRect(rect, paint);
    paint.setColor(mForegroundColor);
    canvas.drawText(text, start, end, x, y, paint);
}

Edit-1

I am using MeasureText:

private float measureText(Paint paint, CharSequence text, int start, int end) { return paint.measureText(text, start, end); }

Edit-2

After some suggestions I made these changes and I can see Rounded corner on Rectangle

@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
    RectF rect = new RectF(x, top, x + measureText(paint, text, start, end), bottom);
    paint.setColor(mBackgroundColor);
    canvas.drawRoundRect(rect, 15,15,paint);
    paint.setColor(mForegroundColor);
    canvas.drawText(text, start, end, x, y, paint);

}

and here is the screenshot:

enter image description here

I am calling draw method from following code:

int currentIndex = 0;
for (int i = 0; i < words.length - 1; i++) {
            s.setSpan(new CustomDrawble(Color.GRAY, Color.WHITE), currentIndex, currentIndex + words[i].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            currentIndex += words[i].length() + 1;
        }

Answer

Blackbelt picture Blackbelt · Oct 24, 2015

Canvas has the method drawRoundRect. You will have to provide the RectF to be drawn, the Paint, as for drawRect and two addition paramters, rx and ry that represent the x and y radius of your rounded corners. E.g.

canvas.drawRoundRect(rect, 5, 5, paint);

will draw a rect with round corner of 5pixels

Edit2:

disclaimer: use dip instead of pixels

@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
   RectF rect = new RectF(x, top, x + measureText(paint, text, start, end) + 10, bottom);
   paint.setColor(mBackgroundColor);
   canvas.drawRoundRect(rect, 15,15,paint);
   paint.setColor(mForegroundColor);
   canvas.drawText(text, start, end, x + 5, y, paint); 
 }