Skip to content

Instantly share code, notes, and snippets.

@imandaliya
Created November 30, 2024 12:14
Show Gist options
  • Select an option

  • Save imandaliya/b93fe56b1ec4c0d161b0ef83b81ce52e to your computer and use it in GitHub Desktop.

Select an option

Save imandaliya/b93fe56b1ec4c0d161b0ef83b81ce52e to your computer and use it in GitHub Desktop.
// Original Thread https://stackoverflow.com/questions/3257293/measuring-text-width-to-be-drawn-on-canvas-android
fun String.getWidth(fontSize: Float): Float {
val textPaint = TextPaint()
textPaint.textSize = fontSize
textPaint.typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
val texts = this.split("\n")
if (texts.size == 1) {
return textPaint.measureText(this)
}
var finalWidth = 0f
for (text in texts) {
val thisLineWidth = text.getWidth(fontSize)
if (thisLineWidth > finalWidth) {
finalWidth = thisLineWidth
}
}
return finalWidth
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment