Android Compose 渐变色Text

在这里插入图片描述

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)

相关推荐

  1. el-progress变色

    2024-03-20 12:28:06       22 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-20 12:28:06       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-20 12:28:06       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-20 12:28:06       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-20 12:28:06       20 阅读

热门阅读

  1. 【大模型学习记录】db-gpt源码安装问题汇总

    2024-03-20 12:28:06       19 阅读
  2. Android学习进阶

    2024-03-20 12:28:06       21 阅读
  3. docker基础(二)之docker build

    2024-03-20 12:28:06       19 阅读
  4. 布隆过滤器的实现及使用

    2024-03-20 12:28:06       19 阅读
  5. 大模型提示工程和常用的几个场景下Prompt案例

    2024-03-20 12:28:06       19 阅读