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 ??
This might be very late for this particular query but I think many will find this answer useful. So, the problem with the Canvas for any CustomView is that, you can get the width for a particular text, but it's not that easy to get the height of the text. Also if you are using
canvas.drawText(....)
with simple Paint object, you can not draw multi line text. So, use the below code within youronDraw()
method.just make sure that, you declare all the objects and variable outside of the
draw()
method. And this will draw a rectangle outline around the text with multi line support. If you want the rectangle to have a fill, then just use the highlightedRectPaint and change thesetStyle(Paint.Style.FILL)
. Hope that helps.Here i have hardcoded x and y values. You can change them
Edit :
Its bad a idea to call
measureText
inonDraw
. You can do that outside ofonDraw
.There is a video on also about performance and why you should avoid allocations in
onDraw
. https://www.youtube.com/watch?v=HAK5acHQ53EResulting snap shot