开发者

Fit a rectangle around a string on an Android Canvas

开发者 https://www.devze.com 2023-03-12 10:28 出处:网络
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 prob

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);

0

精彩评论

暂无评论...
验证码 换一张
取 消