簡體   English   中英

如何在 android compose 中以黑白顯示圖像

[英]How to show Image in black and white in android compose

我正在嘗試使用 android compose 將顯示的彩色圖像轉換為黑白。

在視圖系統中,我可以通過添加這樣的過濾器將圖像從彩色更改為黑白

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

如this answer所示。

在 Android 組合圖像function 已經采用了濾色器,但我在組合 package 中找不到等效的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
        )

我希望我沒有誤解這個問題,但這幫助我將圖像轉換為灰度。 這是根據當前的 Compose 版本 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)
    )

我嘗試了這個答案並為我工作: Convert a Bitmap to GrayScale in Android

所以,你只需要使用toGrayscale function...

這就是我所做的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM