简体   繁体   中英

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
        )

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

I tried this answer and worked for me: Convert a Bitmap to GrayScale in Android

So, you just need to use toGrayscale function...

This is what I did:

@Composable
fun GrayscaleImage() {
    val context = AmbientContext.current
    val image = remember {
        val drawable = ContextCompat.getDrawable(
            context, R.drawable.your_drawable
        ).toBitmap()!!.toGrayScale().asImageBitmap()
    }
    Image(image)
}


object Constants{
    val grayPaint = android.graphics.Paint()
    init {
        val cm = ColorMatrix()
        cm.setSaturation(0f)
        val f = ColorMatrixColorFilter(cm)
        grayPaint.colorFilter = f
    }
}


fun Bitmap.toGrayscale(): Bitmap {
    val height: Int = this.height
    val width: Int = this.width
    val bmpGrayscale: Bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
    val c = Canvas(bmpGrayscale)
    c.drawBitmap(this, 0f, 0f, Constants.grayPaint)
    return bmpGrayscale
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM