Created
June 3, 2019 23:11
-
-
Save glureau/e077c31f50a39101c04ac9221eb90086 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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