Search code examples
androidcanvasviewdrawing

Draw text inside a filled rectangle using Canvas Android


How to draw a filled rectangle with specified bounds and inside that rectangle text to be drawn using Canvas Android ?? I tried

mPaint.setColor(Color.GREEN);
canvas.drawText(mText, x, y, mPaint);
mPaint.setColor(Color.BLACK);
canvas.drawRect(x, y, x + w, y + h, mPaint);

but text is not inside of that rectangle. Can any buddy tell me how to draw a rectangle surrounding specified text with consideration of text size ??


Solution

  • Here i have hardcoded x and y values. You can change them

            mpaint= new Paint();
            mpaint.setColor(Color.RED);
            mpaint.setStyle(Style.FILL);
            paint2= new Paint();
            paint2.setColor(Color.GREEN);
            paint2.setTextSize(50);  //set text size
            float w = paint2.measureText(s)/2;
            float textSize = paint2.getTextSize();
    
    
            @Override
            protected void onDraw(Canvas canvas) {
                paint2.setTextAlign(Paint.Align.CENTER);
                canvas.drawRect(300-w, 300 - textsize, 300 + w, 300, mpaint);
                canvas.drawText(s, 300, 300 ,paint2); //x=300,y=300    
            }
    

    Edit :

    Its bad a idea to call measureText in onDraw. You can do that outside of onDraw.

    There is a video on also about performance and why you should avoid allocations in onDraw. https://www.youtube.com/watch?v=HAK5acHQ53E

    Resulting snap shot

    enter image description here