Can't figure out how to add a gradient to a text with an inner shadow with a modifier in Jetpack Compose. To have something like this? Any ideas?

enter image description here

推荐答案

So far jetpack compose doesn't provide text gradient and inner shadow out of the box. Hence need to paint it by yourself:

result image

@Composable
fun drawGradientText(name: String, modifier: Modifier = Modifier) {

    val paint = Paint().asFrameworkPaint()

    val gradientShader: Shader = LinearGradientShader(
        from = Offset(0f, 0f),
        to = Offset(0f, 400f),
        listOf(Color.Blue, Color.Cyan)
    )

    Canvas(modifier.fillMaxSize()) {
        paint.apply {
            isAntiAlias = true
            textSize = 400f
            typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
            style = android.graphics.Paint.Style.FILL
            color = android.graphics.Color.parseColor("#cdcdcd")
            xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OVER)
            maskFilter = BlurMaskFilter(30f, Blur.NORMAL)
        }
        drawIntoCanvas { canvas ->
            canvas.save()
            canvas.nativeCanvas.translate(2f, 5f)
            canvas.nativeCanvas.drawText(name, 0f, 400f, paint)
            canvas.restore()
            paint.shader = gradientShader
            paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
            paint.maskFilter = null
            canvas.nativeCanvas.drawText(name, 0f, 400f, paint)
            canvas.nativeCanvas.translate(2f, 5f)
            paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OVER)
            paint.maskFilter = BlurMaskFilter(30f, Blur.NORMAL)
            canvas.nativeCanvas.drawText(name, 0f, 400f, paint)
        }
        paint.reset()
    }
}

You can adjust PorterDuff modes and offsets to meet your requirements.

Kotlin相关问答推荐

如何为集成测试配置Gradle JVM测试套件?

数据源配置

Kotlin - 什么时候和什么时候不喜欢内联函数,为什么?

每个 Kotlin 版本的默认 Kotlin 语言版本是什么?

为什么多线程不会使执行更快

从 HashMap 检索时的 NPE,即使 containsKey() 在多线程环境中返回 true

Kotlin spring boot @RequestBody 验证未触发

is return inside function definition 也是 kotlin 中的表达式

Dagger 2 ContributesAndroidInjector 为模块提供活动

Kotlin - 当表达式返回函数类型

Android 在将 androidx 生物识别更新为 1.0.0-alpha04 后崩溃

在 Koin 中提供一个 Instance 作为其接口

Kotlin:sealed class cannot "contain" data classes?

Kotlin:子构造函数如何使用其父构造函数的辅助构造函数?

将ExpectedException与Kotlin一起使用

当被Spring代理类访问时,Kotlin实例变量为null

Kotlin 的 Double.toInt() 中使用了哪种方法,舍入还是截断?

Kotlin:如何修改成对的值?

可以在函数参数中使用解构吗?

Android Jetpack Compose 中的文本渐变