How to -accurately- measure size in pixels of text being drawn on a canvas by drawTextOnPath()
- by Nick
I'm using drawTextOnPath() to display some text on a Canvas and I need to know the dimensions of the text being drawn. I know this is not feasible for paths composed of multiple segments, curves, etc. but my path is a single segment which is perfectly horizontal. I am using Paint.getTextBounds() to get a Rect with the dimensions of the text I want to draw.
I use this rect to draw a bounding box around the text when I draw it at an arbitrary location.
Here's some simplified code that reflects what I am currently doing:
// 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 -close- but not perfect. If I replace the second to last line with:
canvas.drawText(text, startX, startY - vOffset, paint);
Then it works perfectly. Usually there is a gap of 1-3 pixels on the right and bottom edges. The error seems to vary with font size as well. Any ideas? It's possible I'm doing everything right and the problem is with drawTextOnPath(); the text quality very visibly degrades when drawing along paths, even if the path is horizontal, likely because of the interpolation algorithm or whatever its using behind the scenes. I wouldnt be surprised to find out that the size jitter is also coming from there.