目前Jetpack Compose没有开箱即用的文本渐变和内部阴影功能。因此需要自己绘制:
@Composable
fun drawGradientText(name: String, modifier: Modifier = Modifier) {
val paint = Paint().asFrameworkPaint()
val gradientShader: Shader = LinearGradientShader(
from = Offset(0f, 0f),
to = Offset(0f, 400f),
listOf(Color.Blue, Color.Cyan)
)
Canvas(modifier.fillMaxSize()) {
paint.apply {
isAntiAlias = true
textSize = 400f
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
style = android.graphics.Paint.Style.FILL
color = android.graphics.Color.parseColor("#cdcdcd")
xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OVER)
maskFilter = BlurMaskFilter(30f, Blur.NORMAL)
}
drawIntoCanvas { canvas ->
canvas.save()
canvas.nativeCanvas.translate(2f, 5f)
canvas.nativeCanvas.drawText(name, 0f, 400f, paint)
canvas.restore()
paint.shader = gradientShader
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
paint.maskFilter = null
canvas.nativeCanvas.drawText(name, 0f, 400f, paint)
canvas.nativeCanvas.translate(2f, 5f)
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OVER)
paint.maskFilter = BlurMaskFilter(30f, Blur.NORMAL)
canvas.nativeCanvas.drawText(name, 0f, 400f, paint)
}
paint.reset()
}
}
您可以调整PorterDuff模式和偏移量以满足您的要求。
刚好遇到了同样的用例,但只是针对文本上的简单渐变。如果有帮助,我将在此发布。
对我有效的方法是通过Modifier.graphicsLayer
绘制内容和渐变(从Slack上这个答案进行推断):
Text(
text = "$ 20",
/** size/font style, etc. **/
modifier = Modifier.graphicsLayer(alpha = 0.99f)
.drawWithCache {
val brush = Brush.horizontalGradient(listOf(StartColor, EndColor))
onDrawWithContent {
drawContent()
drawRect(brush, blendMode = BlendMode.SrcAtop)
}
}
)
最后我把它制作成修改器
以便重复使用:
fun Modifier.textBrush(brush: Brush) = this
.graphicsLayer(alpha = 0.99f)
.drawWithCache {
onDrawWithContent {
drawContent()
drawRect(brush, blendMode = BlendMode.SrcAtop)
}
}
示例结果:
在Jetpack Compose 1.2.0-beta01中,添加了文本渐变were added。
示例:
@Composable
fun BrushDemo() {
Text(
"Brush is awesome\nBrush is awesome\nBrush is awesome",
style = TextStyle(
brush = Brush.linearGradient(
colors = RainbowColors,
tileMode = TileMode.Mirror
),
fontSize = 30.sp
)
)
}