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.
Asked
Active
Viewed 4,275 times
2 Answers
13
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)

Martin Marinov
- 1,167
- 3
- 15
- 25
-
I've struggled to draw text that center in a rectangle for a while. Thank you very much! – Anh Tuan Aug 29 '11 at 11:10
3
try drawing rectangle using
canvas.drawRect(x, y - Paint.GetTextSize(), x + Paint.measureText("text"), y, Paint);

eyespyus
- 1,576
- 19
- 20
-
I think this would work, though I ended up doing another thing that also worked for me so now I can't try it to see whether this method works. Thank you anyway :) – Martin Marinov Jun 12 '11 at 16:25
-
-
In this context, x and y are where OP is drawing text, answer is to draw a box around this text. – eyespyus Feb 21 '14 at 16:54
-
any soluction to this http://stackoverflow.com/questions/25176321/canvas-drawtext-positioning – Binod Singh Aug 07 '14 at 08:12