这是一种更有效的方法:
private static void setTextSizeForWidth(Paint paint, float desiredWidth, String text) { // Pick a reasonably large value for the test. Larger values produce // more accurate results, but may cause problems with hardware // acceleration. But there are workarounds for that, too; refer to // http://stackoverflow.com/questions/6253528/font-size-too-large-to-fit-in-cache final float testTextSize = 48f; // Get the bounds of the text, using our testTextSize. paint.setTextSize(testTextSize); Rect bounds = new Rect(); paint.getTextBounds(text, 0, text.length(), bounds); // Calculate the desired size as a proportion of our testTextSize. float desiredTextSize = testTextSize * desiredWidth / bounds.width(); // Set the paint for that size. paint.setTextSize(desiredTextSize);}然后,您所要做的就是
setTextSizeForWidth(paint, 400, str);(400为问题中的示例宽度)。
为了获得更高的效率,您可以使它
Rect成为静态类成员,从而避免每次实例化它。但是,这可能会引入并发问题,并且可能会阻碍代码的清晰度。



