Android 提供了一个 autoSizeTextType 属性来自动调整字体大小,但是它仅适用于 API Level 26 及以上的版本。对于 API Level 25 及以下的版本,可以通过代码计算最佳字体大小来实现动态调整。以下是使用 Kotlin 代码实现的示例:
fun getBestFontSize(text: String, maxWidth: Int, maxHeight: Int): Float {val paint = Paint()var textSize = 100f // 初始字体大小,可根据实际情况调整var bound = Rect()paint.textSize = textSizepaint.getTextBounds(text, 0, text.length, bound)while (bound.width() > maxWidth || bound.height() > maxHeight) {textSize -= 1paint.textSize = textSizepaint.getTextBounds(text, 0, text.length, bound)}return textSize
}
该函数的输入是要显示的文本、区域的最大宽度和最大高度,输出是最佳字体大小。使用 paint.getTextBounds() 函数获得文本的实际宽度和高度,并在 while 循环中不断减小字体大小,直到宽度和高度都符合要求。最后返回最佳字体大小即可。在将字体应用于视图之前,还应该将像素值转换为 sp 单位。例如:
val bestFontSize = getBestFontSize("Hello, World!", maxWidth, maxHeight)
val scaledFontSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, bestFontSize, resources.displayMetrics)
textView.textSize = scaledFontSize