Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ??

like image 727
Arjun Kanti Avatar asked Mar 25 '13 07:03

Arjun Kanti


2 Answers

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

like image 92
Raghunandan Avatar answered Nov 11 '22 17:11

Raghunandan


If you have to center the text inside de rect you have use this code

    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);
        Rect rect = new Rect(300-w, 300 - textsize, 300 + w, 300);
        canvas.drawRect(rect, mpaint);
        canvas.drawText(s, rect.centerX(), rect.centerY() ,paint2); // center text inside rect
    }

enter image description here

like image 29
Ricardo López García Avatar answered Nov 11 '22 18:11

Ricardo López García