Set the rectangle around the line on Android canvas

So I use Canvas.drawText to draw some string on a Canvas . The problem is that I want to draw a rectangle in front of it so that the text looks centered on the rectangle. But I ran into a real problem. The x and y coordinates of drawText presented do not really refer to the "upper left" corner of the real text, but rather to the line where the characters begin. There is a Paint.getTextBounds method, which returns the rectangle "with the alleged origin" in (0,0) of the text to be drawn. The problem is that the origin is at (0,0). The width and height of this window is correct, but I do not know how to place its upper left corner in the upper left corner of the line drawn on the canvas. I assume I should use FontMetrics , but since many FontMetrics values are returned, are undocumented. I am not sure how to use them for my purpose.

+5
source share
2 answers

I finished work

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

x, y. x, y paint.measureText()

+12

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

+1

All Articles