Android Compose 渐变色Text

kotlin 复制代码
fun px2dp(scale: Float, px: Int): Int {
//    val scale = resources.displayMetrics.density
    return (px / scale + 0.5f).toInt()
}

@Composable
fun GradientText(
    text: String,
    textSize: Int = 24,
    gradientShader: (Rect) -> Shader = {
        LinearGradientShader(
            from = Offset(0f, 0f),
            to = Offset((it.right - it.left).toFloat(), 0f),
            colors = listOf(Color.White, Color.Blue, Color.Red, Color.Gray, Color.Yellow)
        )
    }
) {
    val density = LocalDensity.current.density
    var width by remember { mutableStateOf(0.dp) }
    var height by remember { mutableStateOf(0.dp) }

    Canvas(
        modifier = Modifier
            .padding(height / 5)
            .width(width)
            .height(height)
    ) {
        drawIntoCanvas { canvas ->
            val paint = Paint().asFrameworkPaint().apply {
                this.isAntiAlias = true
                this.style = android.graphics.Paint.Style.FILL
//                this.shader = gradientShader
                this.textSize = textSize * density
            }
            val rect = Rect()
            paint.getTextBounds(text, 0, text.length, rect)

            width = px2dp(density, rect.right - rect.left).dp
            height = px2dp(density, rect.bottom - rect.top).dp

            paint.shader = gradientShader.invoke(rect)

            val fontMetrics = paint.fontMetrics
            val distance = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom
            canvas.nativeCanvas.drawText(
                text,
                0f,
                size.height / 2 + distance,
                paint
            )
        }
    }
}

@Preview
@Composable
fun Pppp() {
    GradientText(text = "Chinese Great jjj", textSize = 24)
相关推荐
恋猫de小郭13 分钟前
Flutter 在 iOS 26 模拟器跑不起来?其实很简单
android·前端·flutter
尤老师FPGA40 分钟前
使用ZYNQ芯片和LVGL框架实现用户高刷新UI设计系列教程(第三十二讲)
android·java·ui
叫我龙翔1 小时前
【MySQL】从零开始了解数据库开发 --- 复合查询
android·mysql·数据库开发
Kapaseker1 小时前
Compose 中实现凸角、凹角、切角、尖角
android·kotlin
Erwinl2 小时前
android 开机启动 无线调试
android
此生只爱蛋2 小时前
mysql_store_result
android·adb
双桥wow3 小时前
Android Framework开机动画开发
android
fanged10 小时前
天马G前端的使用
android·游戏
molong93114 小时前
Kotlin 内联函数、高阶函数、扩展函数
android·开发语言·kotlin
叶辞树15 小时前
Android framework调试和AMS等服务调试
android