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 re开发者_Go百科al 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.
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)
try drawing rectangle using
canvas.drawRect(x, y - Paint.GetTextSize(), x + Paint.measureText("text"), y, Paint);
精彩评论