直接上代码
private float getOptimizedTextSize(Bitmap bitmap, String importer, String importTime, float textWidth) {
TextPaint textPaint = new TextPaint();
textPaint.setAntiAlias(true);
textPaint.setTextSize(10f); // 设置一个较小的初始字体大小
float maxTextSize = bitmap.getHeight() / 2f; // 最大字体大小为图片高度的一半
// 逐步逼近,每次调整步进值减半
float step = maxTextSize / 2f;
boolean isTwoLines = importer.contains("\n") || importer.length() + importTime.length() > textWidth;
while (step > 0.1f && isTwoLines) {
StaticLayout staticLayout = new StaticLayout(importer + "\n" + importTime,
textPaint,
(int) Math.ceil(textWidth),
Layout.Alignment.ALIGN_NORMAL,
1.0f, // 行间距倍数
0.0f, // 字间距
false);
// 检查当前字体大小是否合适
if (staticLayout.getLineCount() != 2) {
// 如果不是两行,则强制插入换行符并重新计算
isTwoLines = false;
continue;
} else if (staticLayout.getHeight() > bitmap.getHeight()) {
maxTextSize -= step;
} else if (staticLayout.getHeight() < bitmap.getHeight() - step) {
maxTextSize += step;
} else {
// 当前字体大小几乎完美匹配,可以直接跳出循环
break;
}
textPaint.setTextSize(maxTextSize);
step /= 2f;
}
return maxTextSize;
}