アンドロイドコンポーズで画像を白黒で表示する方法

Dec 02 2020

androidcomposeを使用して表示されているカラー画像を白黒に変換しようとしています。

ビューシステムでは、このようなフィルターを追加することで、画像をカラーから白黒に変更できます。

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

この回答に示されているように。

Android Composeでは、Image composable関数はすでにカラーフィルターを使用していますが、composeパッケージに同等のColorMatrixColorFilterが見つかりません。

これが私がグレースケールに変換したい画像コードです

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

回答

nglauber Jan 09 2021 at 20:59

私はこの答えを試し、私のために働きました:Androidでビットマップをグレースケールに変換する

だから、あなたはただtoGrayscale関数を使う必要があります...

これは私がしたことです:

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