Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show Image in black and white in android compose

I am trying to convert the colored Image shown to black and white using android compose.

In the view system, I could change the image from colored to black and white by adding a filter like that

imageView.colorFilter = ColorMatrixColorFilter(ColorMatrix().apply { setSaturation(0f)})

as shown in this answer.

In Android Compose the Image composable function already takes color filter but I cannot find ColorMatrixColorFilter equivalent in the compose package.

Here is the Image code that I want to convert to grayscale

 Image(
            asset = vectorResource(id = R.drawable.xxx),
            modifier = Modifier.clip(RectangleShape).size(36.dp, 26.dp),
            alpha = alpha,
            alignment = Alignment.Center,
            contentScale = ContentScale.Fit
        )
like image 920
David Ibrahim Avatar asked Dec 02 '20 07:12

David Ibrahim


1 Answers

I hope I have not misunderstood the problem but this helped me convert the image into grayscale. This is as per the current Compose version 1.0.0-beta01

val grayScaleMatrix = ColorMatrix(
        floatArrayOf(
            0.33f, 0.33f, 0.33f, 0f, 0f,
            0.33f, 0.33f, 0.33f, 0f, 0f,
            0.33f, 0.33f, 0.33f, 0f, 0f,
            0f, 0f, 0f, 1f, 0f
        )
    )
Image(
        painter = painterResource(id = imageId),
        contentDescription = "",
        colorFilter = ColorFilter.colorMatrix(matrix)
    )
like image 59
Shubhayu Avatar answered Nov 08 '22 06:11

Shubhayu