Android रचना में काले और सफेद में छवि कैसे दिखाएं

Dec 02 2020

मैं एंड्रॉइड कम्पोज़ का उपयोग करके काले और सफेद को दिखाए गए रंगीन छवि को बदलने की कोशिश कर रहा हूं।

व्यू सिस्टम में, मैं उस तरह का फ़िल्टर जोड़कर छवि को काले और सफेद से बदल सकता हूं

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

जैसा कि इस उत्तर में दिखाया गया है ।

एंड्रॉइड कम्पोज़ में इमेज कंपोजेबल फंक्शन पहले से ही कलर फिल्टर ले लेता है, लेकिन मुझे कंपोज़ पैकेज में 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

मैंने इस उत्तर की कोशिश की और मेरे लिए काम किया: एंड्रॉइड में एक बिटमैप को ग्रेस्केल में बदलें

तो, आपको बस 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
}