How to accurately measure the size in pixels of text drawn on canvas drawTextOnPath ()

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.

+4
source share
1 answer

I found a solution that works for my specific situation, although it really does not resolve the original question.

Since my specific use case only draws text along single-line straight tracks, I was able to completely get rid of all the paths and use Canvas.drawText () along with Canvas.translate () and canvas.rotate (). This saved me from the randomness and ugliness of the text size that I saw when drawing along the tracks.

0
source

Source: https://habr.com/ru/post/1334840/


All Articles