Note once that ImageSpan is centered below API 29
describe
Without explanation, look at the picture below:
Analysis of the
Since you can use imagespan. ALIGN_CENTER on API 29, let’s take a look at the source code implementation, pull out the necessary code, write an ImageSpanUnderQ class and use it below 29.
Source code analysis:
The red box part makes our key code and simple process: first, get the current Drawable, second, calculate the translation distance of Canvas and move it, so as to draw the current picture in the center, and finally b.draw(Canvas) to draw it.
To deal with
The source code is as follows:
class ImageSpanUnderQ(drawable: Drawable) : ImageSpan(drawable) {
private var mDrawableRef: WeakReference<Drawable>? = null
override fun draw(canvas: Canvas, text: CharSequence? , start:Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) {
valb: Drawable = getCachedDrawable() ? :return
canvas.save()
val transY = (bottom - top) / 2 - b.bounds.height() / 2
canvas.translate(x, transY.toFloat())
b.draw(canvas)
canvas.restore()
}
private fun getCachedDrawable(a): Drawable? {
val wr: WeakReference<Drawable>? = mDrawableRef
var d: Drawable? = null
if(wr ! =null) {
d = wr.get()}if (d == null) {
d = drawable
mDrawableRef = WeakReference(d)
}
return d
}
}
Copy the code
conclusion
The problem is not very difficult to meet more thinking and find a breakthrough from the source ~
Guys, Peace & Love