如何在Android Compose中显示黑白图像

7

我正在尝试使用Android Compose将彩色图像转换为黑白图像。

在视图系统中,我可以通过添加过滤器来将图像从彩色变为黑白,例如:

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

答案所示。

在Android Compose中,Image可组合功能已经具有颜色过滤器,但我找不到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
        )
2个回答

9
我希望我没有误解问题,但这对我有所帮助,将图像转换为灰度。 这符合当前的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)
    )

2
你可以解释一下你的代码吗,特别是那个grayScaleMatrix的值? - David Ibrahim

0

我尝试了这个答案,对我有用: 在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
}

我正在使用可绘制对象而不是位图,因此无法使用BitmapFactory.decodeResource(context.resources, R.drawable.ic_launcher) - David Ibrahim
1
你可以将任何Drawable转换为Bitmap... 现在,androidx核心库(androidx.core:core-ktx)有一个扩展函数来实现这一点... 我尝试了ShapeDrawable,它可以工作... - nglauber

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接