从 SDK 版本 28 以下的 TypeFace 创建 TypeFaceSpan



我找到了一种从TypeFace create TypeFaceSpan的方法,如下所示:

fun getTypeFaceSpan(typeFace:TypeFace) = TypeFaceSpan(typeFace)

此 API 仅在 API 级别>= 28允许。有没有兼容图书馆来实现低于 28 的这个目标?

TypeFaceSpan是一个MetricAffectingSpan。因此,即使没有任何确切的方法TypeFaceSpan可以从 Span我们可以制作如下所示的CustomTypeFaceSpan并用它来代替TypeFaceSpan

class CustomTypefaceSpan(private val typeface: Typeface?) : MetricAffectingSpan() {
    override fun updateDrawState(paint: TextPaint) {
        paint.typeface = typeface
    }
    override fun updateMeasureState(paint: TextPaint) {
        paint.typeface = typeface
    }
}

并像这样使用它:

val typeFaceSpan = CustomTypefaceSpan(typeface)

灵感来自 @erluxman 的答案,并与 Kotlin 的扩展函数相结合:

fun Typeface.getTypefaceSpan(): MetricAffectingSpan {
    return if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.P) typefaceSpanCompatV28(this) else CustomTypefaceSpan(this)
}
@TargetApi(Build.VERSION_CODES.P)
private fun typefaceSpanCompatV28(typeface: Typeface) =
    TypefaceSpan(typeface)

private class CustomTypefaceSpan(private val typeface: Typeface?) : MetricAffectingSpan() {
    override fun updateDrawState(paint: TextPaint) {
        paint.typeface = typeface
    }
    override fun updateMeasureState(paint: TextPaint) {
        paint.typeface = typeface
    }
}

然后你可以像这样使用它:

typeface.getTypefaceSpan()

相关内容

  • 没有找到相关文章

最新更新