Question

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.

Was it helpful?

Solution

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)

OTHER TIPS

try drawing rectangle using

canvas.drawRect(x, y - Paint.GetTextSize(), x + Paint.measureText("text"), y, Paint);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top