Skip to content

Instantly share code, notes, and snippets.

@Andrew0000
Last active November 22, 2022 15:28
Show Gist options
  • Save Andrew0000/8add900c39a3473d918cd06e165fd7e4 to your computer and use it in GitHub Desktop.
Save Andrew0000/8add900c39a3473d918cd06e165fd7e4 to your computer and use it in GitHub Desktop.
TextMeasure
import android.graphics.Paint
import android.util.TypedValue
import android.widget.TextView
/**
* Use it for [android.widget.EditText], because on it autoSize doesn't work
*/
class TextMeasure(
private val textView: TextView,
private val maxSize: Float = 24.dp.toFloat(),
private val minSize: Float = 2.dp.toFloat(),
private val step: Float = 2.dp.toFloat(),
) {
private val paint = Paint().also {
it.typeface = textView.typeface
it.letterSpacing = textView.letterSpacing
}
fun adjustTextSizeToMaxWidth(maxWidth: Int) {
var size = textView.textSize
var measuredWidth = measureTextWidthPx(size)
if (measuredWidth > maxWidth) {
while (true) {
size -= step
size = size.coerceAtLeast(minSize)
measuredWidth = measureTextWidthPx(size)
if (measuredWidth <= maxWidth || size <= minSize) {
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, size)
return
}
}
}
if (measuredWidth < maxWidth) {
var sizePrev = size
while (true) {
size += step
size = size.coerceAtMost(maxSize)
measuredWidth = measureTextWidthPx(size)
if (measuredWidth > maxWidth) {
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, sizePrev)
return
}
if (size == maxSize) {
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, size)
return
}
sizePrev = size
}
}
}
private fun measureTextWidthPx(textSize: Float): Float {
paint.textSize = textSize
var string = textView.text?.toString() ?: ""
if (string.isEmpty()) {
string = textView.hint?.toString() ?: ""
}
return paint.measureText(string)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment