Created
June 19, 2018 00:34
-
-
Save justasm/b682e77b36faabfc6e6f97a2e4f531cd to your computer and use it in GitHub Desktop.
Image / drawable span that is vertically centered relative to its surrounding text
This file contains hidden or 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
private abstract class CenterVerticalDrawableSpan : ReplacementSpan() { | |
abstract fun getDrawable(): Drawable? | |
private var drawableRef: WeakReference<Drawable>? = null | |
private val cachedDrawable: Drawable? | |
get() = drawableRef?.get() ?: getDrawable()?.also { drawableRef = WeakReference(it) } | |
override fun getSize(paint: Paint, text: CharSequence, | |
start: Int, end: Int, fm: Paint.FontMetricsInt?): Int { | |
val drawable = cachedDrawable ?: return 0 | |
val bounds = drawable.bounds | |
if (fm != null) { | |
val height = bounds.height() | |
val bottom = fm.descent + (height - (fm.descent - fm.ascent)) / 2 | |
val top = bottom - height | |
fm.descent = bottom | |
fm.bottom = bottom | |
fm.ascent = top | |
fm.top = top | |
} | |
return bounds.width() | |
} | |
override fun draw(canvas: Canvas, text: CharSequence, | |
start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) { | |
val drawable = cachedDrawable ?: return | |
canvas.apply { | |
save() | |
translate(x, 0f) | |
drawable.draw(this) | |
restore() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment