TextView with background color and line spacing

前端 未结 6 630
小蘑菇
小蘑菇 2020-12-06 11:06

I\'d like to show the text like the below...

\"enter

My coding is the followin

6条回答
  •  一生所求
    2020-12-06 11:47

    Based on @evren-ozturk answer without textView link and better typography support

    class RoundedBackgroundSpan(
        private val textColor: Int,
        private val backgroundColor: Int
    ) : ReplacementSpan() {
    
        private val additionalPadding = 4.toPx().toFloat()
        private val cornerRadius = 4.toPx().toFloat()
    
        override fun draw(
            canvas: Canvas,
            text: CharSequence,
            start: Int,
            end: Int,
            x: Float,
            top: Int,
            y: Int,
            bottom: Int,
            paint: Paint
        ) {
            val newTop = y + paint.fontMetrics.ascent
            val newBottom = y + paint.fontMetrics.descent
            val rect = RectF(x, newTop, x + measureText(paint, text, start, end) + 2 * additionalPadding, newBottom)
            paint.color = backgroundColor
    
            canvas.drawRoundRect(rect, cornerRadius, cornerRadius, paint)
            paint.color = textColor
            canvas.drawText(text, start, end, x + additionalPadding, y.toFloat(), paint)
        }
    
        override fun getSize(paint: Paint, text: CharSequence?, start: Int, end: Int, fm: FontMetricsInt?): Int {
            return (paint.measureText(text, start, end) + 2 * additionalPadding).roundToInt()
        }
    
        private fun measureText(paint: Paint, text: CharSequence, start: Int, end: Int): Float {
            return paint.measureText(text, start, end)
        }
    
        private fun Int.toPx(): Int {
            val resources = Resources.getSystem()
            val metrics = resources.displayMetrics
            return Math.round(this * (metrics.densityDpi / 160.0f))
        }
    }
    

提交回复
热议问题