合成图像/图标渐变色调



是否可以在合成布局中使用渐变对vectorImage进行着色?看起来Modifier.background为它创建了一个背景,所以它不是一个解决方案。ColorFilter like还不支持它。

更新

有一个更简单的解决方案,它取自@nebulasmoothie对Android Jetpack Compose 中文本梯度的回答

Icon(
modifier = Modifier
.graphicsLayer(alpha = 0.99f)
.drawWithCache {
onDrawWithContent {
drawContent()
drawRect(brushGradient, blendMode = BlendMode.SrcAtop)
}
},
imageVector =  Icons.Default.Favorite,
contentDescription = null,
)

ImageVector通过RenderVectorGroup渲染,可以为每个VectorPath传递一个VectorConfig。文档指出它应该用于动画,所以我不确定将它用于渐变是否有效,但这是我发现的唯一可以传递Brush的地方。

实现VectorConfig并使其返回VectorProperty的梯度。填充:

class GradientConfig(private val brush: Brush) : VectorConfig {
override fun <T> getOrDefault(property: VectorProperty<T>, defaultValue: T): T {
return when (property) {
is VectorProperty.Fill -> brush as T
else -> super.getOrDefault(property, defaultValue)
}
}
}
@Composable
fun GradientIcon(image: ImageVector, gradientConfig: GradientConfig) {
val configs = hashMapOf<String, VectorConfig>(image.root.name to gradientConfig)
Icon(
painter = rememberVectorPainter(image = image, configs = configs),
contentDescription = null,
)
}
@Composable
fun rememberVectorPainter(image: ImageVector, configs: Map<String, VectorConfig>): VectorPainter {
return androidx.compose.ui.graphics.vector.rememberVectorPainter(
defaultWidth = image.defaultWidth,
defaultHeight = image.defaultHeight,
viewportWidth = image.viewportWidth,
viewportHeight = image.viewportHeight,
name = image.name,
tintColor = image.tintColor,
tintBlendMode = image.tintBlendMode,
content = { _, _ -> RenderVectorGroup(group = image.root, configs = configs) }
)
}
@Preview(name = "GradientIcon")
@Composable
fun PreviewGradientIcon() {
val gradient = Brush.linearGradient(
colors = listOf(
Color(0xff9F5CFF),
Color(0xffF0A966)
),
start = Offset(12f, 0f),
end = Offset(12f, 24f),
)
GradientIcon(
icon = Icons.Filled.Palette,
gradientConfig = GradientConfig(gradient)
)
}  

最新更新