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)