Created
January 9, 2020 01:25
-
-
Save m4kvn/768a041c4f3437882c6fd30fbe10e4a5 to your computer and use it in GitHub Desktop.
画像を文字のascentとbaselineの中央に配置するImageSpan
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
class CenteredImageSpan( | |
context: Context, | |
resourceId: Int | |
) : ImageSpan(context, resourceId) { | |
private val drawableRef = AtomicReference<Drawable?>() | |
private val cachedDrawable: Drawable | |
get() = drawableRef.get() ?: drawable.apply { | |
drawableRef.set(drawable) | |
} | |
override fun draw( | |
canvas: Canvas, | |
text: CharSequence?, | |
start: Int, | |
end: Int, | |
x: Float, | |
top: Int, | |
y: Int, | |
bottom: Int, | |
paint: Paint | |
) { | |
val d = cachedDrawable | |
canvas.save() | |
val fontAscent = paint.fontMetricsInt.ascent | |
val transY = y + fontAscent - (d.intrinsicHeight + fontAscent) / 2f | |
canvas.translate(x, transY) | |
d.draw(canvas) | |
canvas.restore() | |
} | |
override fun getSize( | |
paint: Paint, | |
text: CharSequence?, | |
start: Int, | |
end: Int, | |
fm: Paint.FontMetricsInt? | |
): Int { | |
val d = cachedDrawable | |
val rect = d.bounds | |
if (fm != null) { | |
val pfm = paint.fontMetricsInt | |
fm.ascent = pfm.ascent | |
fm.descent = pfm.descent | |
fm.top = pfm.top | |
fm.bottom = pfm.bottom | |
} | |
return rect.right | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment