1

我正在制作一个动画,其中涉及将 OutlineSpan 设置为 word 中的单个字母。但是,当我将 OutlineSpan 应用于第一个字母时,它没有反映

val string = "f"
val spannableString = SpannableString(string)
val outlineSpan = OutlineSpan(255, ContextCompat.getColor(this, R.color.white), 1f.dp)
//val outlineSpan = ForegroundColorSpan( ContextCompat.getColor(this, R.color.white))
spannableString.setSpan(outlineSpan, 0, 1, 0)
textViewHollow.setText(spannableString)

当我尝试应用另一个跨度时,它正在工作,但不是轮廓跨度。代码大纲范围https://gist.github.com/santaevpavel/61eb23092bdb8a926aeb8302ec95b4b6

4

1 回答 1

0

我浏览了大纲文本的实际库。这里:https ://github.com/santaevpavel/OutlineSpan

我发现了一个新的更新版本OutlineSpan。您可以使用以下内容替换您的版本。

class OutlineSpan(
    @ColorInt private val strokeColor: Int,
    @Dimension private val strokeWidth: Float
): ReplacementSpan() {

    override fun getSize(
        paint: Paint,
        text: CharSequence,
        start: Int,
        end: Int,
        fontMetrics: Paint.FontMetricsInt?
    ): Int {
        if (fontMetrics != null && paint.fontMetricsInt != null) {
            fontMetrics.bottom = paint.fontMetricsInt.bottom
            fontMetrics.top = paint.fontMetricsInt.top
            fontMetrics.descent = paint.fontMetricsInt.descent
            fontMetrics.leading = paint.fontMetricsInt.leading
        }
        return paint.measureText(text.toString().substring(start until end)).toInt()
    }


    override fun draw(
        canvas: Canvas,
        text: CharSequence,
        start: Int,
        end: Int,
        x: Float,
        top: Int,
        y: Int,
        bottom: Int,
        paint: Paint
    ) {
        val originTextColor = paint.color

        paint.apply {
            color = strokeColor
            style = Paint.Style.STROKE
            this.strokeWidth = this@OutlineSpan.strokeWidth
        }
        canvas.drawText(text, start, end, x, y.toFloat(), paint)

        paint.apply {
            color = originTextColor
            style = Paint.Style.FILL
        }
        canvas.drawText(text, start, end, x, y.toFloat(), paint)
    }

}

然后像这样使用它:

val string = "f"
        val spannableString = SpannableString(string)
        val outlineSpan = OutlineSpan(ContextCompat.getColor(this, R.color.colorAccent), 3f)
        spannableString.setSpan(outlineSpan, 0, 1, 0)
        textViewHollow.text = spannableString

这解决了这个问题。

输出:

轮廓跨度

于 2022-01-20T14:46:56.657 回答