I am using drawTextOnPath () to display some text on the canvas, and I need to know the sizes of the displayed text. I know that this is not possible for paths consisting of several segments, curves, etc., but my path is a separate segment, which is absolutely horizontal. I use Paint.getTextBounds () to get a Rect with the dimensions of the text I want to draw.
I use this rectangle to draw a bounding box around the text when I draw it in an arbitrary place.
Here is some simplified code that reflects what I'm doing now:
// to keep this example simple, always at origin (0,0) public drawBoundedText(Canvas canvas, String text, Paint paint) { Rect textDims = new Rect(); paint.getTextBounds(text,0, text.length(), textDims); float hOffset = 0; float vOffset = paint.getFontMetrics().descent; // vertically centers text float startX = textDims.left; / 0 float startY = textDims.bottom; float endX = textDims.right; float endY = textDims.bottom; path.moveTo(startX, startY); path.lineTo(endX, endY); path.close(); // draw the text canvas.drawTextOnPath(text, path, 0, vOffset, paint); // draw bounding box canvas.drawRect(textDims, paint); }
The results are "closed", but not perfect. If I replaced the second with the last line:
canvas.drawText(text, startX, startY - vOffset, paint);
Then it works fine. Usually on the right and bottom edges there is a gap of 1-3 pixels. Probably the error also varies with the font size. Any ideas? Maybe I'm doing everything right, and the problem is drawTextOnPath (); text quality deteriorates very much when drawing along tracks, even if the path is horizontal, probably due to the interpolation algorithm or the fact that it uses behind the scenes. I would not be surprised to know that the size of the jitter also comes from there.