I now was also busy with this problem.
Unfortunately I didn't manage to install the native source yet, but I'm pretty sure that text measurements (both getTextBounds() and measureText()) differ heftily from the real text output, especially for small font sizes (as to be seen in Moritz' screenshot).
I suppose that the measurement methods use a float width for a char, and the real text output uses an int (presumably due to performance). This will of course fail, if you need an absolutely exact size (e.g for autosize).
I experimented a bit with a monospace font. This Image shows some of these experiments:
.
The text scale in these experiments was set by auto scaling it.
In the top row, I created boxes with an integer increment. These match the android text output. You see, the last cipher doesn't match the screen!
In the 2nd row, the boxes were created with a float increment. The boxes match the screen better, but they don't match the android text output!
In the last row, the boxes were incremented by a float increment and the text was output char by char by the same increment. Both boxes and chars fit perfect.
In my conclusion, it is currently not possible to set an Android text output to an exact width. The problem seems not to be the measurement methods, which are exact enough. The problem seems to be, that you can not set an exact text width by setTextSize().
Try the following to reproduce this:
float width = 100; // define a width which should be achieved
m_textPaint.setTextSize( 100 ); // set a text size surely big enough
Rect r = new Rect();
String s = new String("This is a test text");
m_textPaint.getTextBounds( s, 0, s.length(), r ); // measure the text with a random size
float fac = width / r.width(); // compute the factor, which will scale the text to our target width
Log.i( "MyTestOutput", "current text width:" + r.width() );
Log.i( "MyTestOutput", "wanted text width:" + width );
Log.i( "MyTestOutput", "factor:" + fac );
Log.i( "MyTestOutput", "expected result:" + (float) r.width() * fac );
m_textPaint.setTextSize( m_textPaint.getTextSize() * fac );
m_textPaint.getTextBounds( s, 0, s.length(), r ); // now final measurement: whats the real width?
Log.i( "MyTestOutput", "real result:" + r.width() );
I get an output of:
05-26 12:18:18.420: I/MyTestOutput(23607): current text width:1125
05-26 12:18:18.425: I/MyTestOutput(23607): wanted text width:100.0
05-26 12:18:18.425: I/MyTestOutput(23607): factor:0.08888889
05-26 12:18:18.425: I/MyTestOutput(23607): expected result:100.0
05-26 12:18:18.430: I/MyTestOutput(23607): real result:94
So in my opinion, the only way to achieve very exactly autoscaled text, is to
a) autoscale it by measuring and setting text size
b) output it char by char by a self computed increment.
Unfortunately, this works only for monospaced fonts. For other fonts, it will be more complicated, but also possible.