Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fit a rectangle around a string on an Android Canvas

So I use Canvas.drawText to draw some string on a Canvas. The issue is that I want to draw a rectangle before it so that the text appears centred onto the rectangle. But I hit a real problem. The supplied x and y coordinates to drawText actually are not of the "top left" corner of the real text, but rather on the line where the characters begin. There is a method Paint.getTextBounds which returns a rectangle "with implied origin" at (0,0) of the text that would be drawn. The issue is that the origin is at (0,0). The width and the height of that box are correct but I don't know how to place its top left corner at the top left corner of the string that is drawn on the canvas. I guess I should use FontMetrics, but since a lot of the values FontMetrics returns are undocumented I'm not really sure how to use them for my purpose.

like image 399
Martin Marinov Avatar asked Jun 11 '11 17:06

Martin Marinov


1 Answers

I ended up doing

FontMetrics fm = new FontMetrics();
paint.setTextAlign(Paint.Align.CENTER);
paint.getFontMetrics(fm);
canvas.drawText(text, x, y + -(fm.ascent + fm.descent) / 2, paint);

Which actually draws the text centered at x, y. Before that I draw a rectangle centered at x, y with width paint.measureText(text)

like image 140
Martin Marinov Avatar answered Sep 24 '22 23:09

Martin Marinov