简体   繁体   中英

How can I get rid of unwanted space over ImageSpan that appears if I also add text to EditText?

How can I get rid of unwanted space over ImageSpan that appears if I add text to EditText?

In EditText , a single ImageSpan takes the whole height, but if I add any text, unwanted space appears over the image, and height of the EditText changes. Can I avoid that?

截屏

It appears that the height of the EditText is calculated as the difference between the minimum top of the text and the maximum bottom. Direction in the font metrics is downwards, and 0 is the base line of the text.

In the left screenshot, as set by DynamicDrawableSpan.getSize() , bottom is 0, and top is -250, which is the image height. That gives us the height of 250.

In the right screenshot, the additional text sets the bottom to 15. Top is still at -250. The height becomes 265 pixels. ImageSpan still draws from the bottom, so you get this weird space.

I'm not sure if this is the best solution but this works for my use case:

class FullHeightImageSpan(
    val context: Context,
    val bitmap: Bitmap
) : ImageSpan(context, bitmap) {
    override fun getSize(paint: Paint, text: CharSequence?, 
                         start: Int, end: Int, 
                         fm: Paint.FontMetricsInt?): Int {
        val oldBottom = fm?.bottom
        val result = super.getSize(paint, text, start, end, fm)
        fm?.apply {
            top += oldBottom!!
            ascent = top
            bottom = oldBottom
        }
        return result
    }
}

Here I'm simply preserving the bottom of the text instead of setting it to 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM