当前位置:   article > 正文

Android Compose 渐变色Text

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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/273583
推荐阅读
相关标签
  

闽ICP备14008679号