Compose image/icon gradient tint

Viewed 1291

Is it possible to tint a vectorImage with gradient in compose layout? Seems like Modifier.background creates a background for it so its not a solution. ColorFilter like is not supporting it yet.

1 Answers

Update:

There is a much simpler solution which is taken from @nebulasmoothie's answer to Text Gradient in 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 is rendered via RenderVectorGroup, which can be passed a VectorConfig for each VectorPath. The docs state it is supposed to be used for animations, so I'm not sure if it is a valid approach to use it for gradients, but it's the only place that I've found where you can pass a Brush.

Implement VectorConfig and make it return your gradient for VectorProperty.Fill:

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)
    )
}  
Related