Skip to content

Instantly share code, notes, and snippets.

@glureau
Created June 3, 2019 23:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glureau/e077c31f50a39101c04ac9221eb90086 to your computer and use it in GitHub Desktop.
Save glureau/e077c31f50a39101c04ac9221eb90086 to your computer and use it in GitHub Desktop.
interface DrawableHeightComputeMode {
fun computeHeight(textPaint: TextPaint, text: CharSequence): Int
}
fun TextView.alignImageToText(textPaint: TextPaint, drawableHeightComputer: DrawableHeightComputeMode) {
(text as? SpannedString)?.getSpans(0, text.length, DynamicDrawableSpan::class.java)?.forEach {
val drawable = it.drawable
val ratio = drawable.intrinsicWidth.toFloat() / drawable.intrinsicHeight
val fontHeight = drawableHeightComputer.computeHeight(textPaint, text)
val drawableWidth = truncate(fontHeight * ratio).toInt()
drawable.setBounds(0, 0, drawableWidth, fontHeight)
}
}
//Example of DrawableHeightComputeMode
class AscentDrawableHeightComputeMode : DrawableHeightComputeMode {
override fun computeHeight(textPaint: TextPaint, text: CharSequence): Int {
return -textPaint.fontMetricsInt.ascent
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment