Comment afficher l'image en noir et blanc dans Android Composer

Dec 02 2020

J'essaie de convertir l'image colorée affichée en noir et blanc à l'aide d'Android compose.

Dans le système de vue, je pourrais changer l'image de couleur en noir et blanc en ajoutant un filtre comme celui-là

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

comme indiqué dans cette réponse .

Dans Android Compose, la fonction composable Image prend déjà en charge le filtre de couleur, mais je ne trouve pas l' équivalent ColorMatrixColorFilter dans le package de composition.

Voici le code d'image que je souhaite convertir en niveaux de gris

 Image(
            asset = vectorResource(id = R.drawable.xxx),
            modifier = Modifier.clip(RectangleShape).size(36.dp, 26.dp),
            alpha = alpha,
            alignment = Alignment.Center,
            contentScale = ContentScale.Fit
        )

Réponses

nglauber Jan 09 2021 at 20:59

J'ai essayé cette réponse et j'ai travaillé pour moi: convertir un bitmap en GrayScale sous Android

Donc, il vous suffit d'utiliser la toGrayscalefonction ...

C'est ce que j'ai fait:

@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
}