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)
相关推荐
2501_916008892 分钟前
深入理解 iPhone 文件管理,从沙盒结构到开发调试的多工具协同实践
android·ios·小程序·https·uni-app·iphone·webview
千里马学框架8 分钟前
聊一聊豆包AI手机助手高度敏感权限CAPTURE_SECURE_VIDEO_OUTPUT
android·ai·智能手机·安卓framework开发·车载开发·豆包手机助手
正经教主30 分钟前
【Trae+AI】和Trae学习搭建App_1.2:第2章·App开发环境配置
android·学习·android studio
pandarking39 分钟前
[CTF]攻防世界:love_math
android·web安全·网络安全
非凡ghost42 分钟前
Brightness.Manager.OK(显示器亮度调节软件)
android·智能手机·计算机外设·软件需求
_李小白1 小时前
【Android FrameWork】延伸阅读:MediaRecorder状态机
android
陌sr,1 小时前
关于TMK的生成及安全注入方式
android·运维·服务器·安全·pos机·edc·刷卡
键来大师1 小时前
Android16 RK3576 系统清理缓存
android·缓存·framework·rk3588·android15
私人珍藏库1 小时前
[吾爱大神原创工具] PPT演讲倒计时工具 高级专业版 v2.0
android·app·工具·ppt·辅助
2501_916007471 小时前
没有 Mac,如何在 Windows 上架 iOS 应用?一套可落地的工程方案
android·macos·ios·小程序·uni-app·iphone·webview